Newbie Question

2007-02-08 Thread Reid
Hello all

I am just starting to play with programing again as a hobby. I have heard 
good things about python. I have not really looked into the language much. 
My question is, will python make programs with a gui under windows xp. If it 
will do this I will explore the language more, if not I will try some other 
language.

Reid


-- 
http://mail.python.org/mailman/listinfo/python-list


Thanks for the help

2007-02-08 Thread Reid
Hello All

Thanks for taking the time to answer my question. I do not need 3d stuff. 
Just a couple of buttons and menu's. The reason I am looking at python is it 
is free to download. I cannot afford VB or other commercial languages.

Reid


-- 
http://mail.python.org/mailman/listinfo/python-list


warnings filters for varying message

2013-06-27 Thread John Reid
Looking at the docs for warnings.simplefilter
(http://docs.python.org/2/library/warnings.html) I think the following
script should only produce one warning at each line as any message is
matched by the simple filter

import warnings
warnings.simplefilter('default')
for i in xrange(2):
warnings.warn('Warning message') # This prints 1 warning
warnings.warn("Warning %d" % i)  # This prints 2 warnings

What do I need to do to get the warnings module just to print one
warning for the second warnings.warn line?

Thanks,
John.

-- 
http://mail.python.org/mailman/listinfo/python-list


Access descendant class's module namespace from superclass

2005-07-11 Thread Reid Priedhorsky
Dear group,

I'd have a class defined in one module, which descends from another class
defined in a different module. I'd like the superclass to be able to
access objects defined in the first module (given an instance of the first
class) without importing it. Example of what I'm looking for:

<<>>

   class Spam(object):
  def fish(self):
 a = self.__module__.Ham()

<<>>

   import spam

   class Eggs(spam.Spam):
  pass

   class Ham(object):
  pass

The above doesn't work because __module__ is a string, not a module object: 

   >>> import eggs
   >>> b = eggs.Eggs()
   >>> b.fish()
   Traceback (most recent call last):
 File "", line 1, in ?
 File "spam.py", line 3, in foo
   a = self.__module__.Ham()
   AttributeError: 'str' object has no attribute 'Ham'

(I suppose I could call __import__(self.__module__), but that seems kind
of awkward.)

Is this possible using Python 2.3? Any better ways to accomplish this?

Thanks very much for any help,

Reid
-- 
http://mail.python.org/mailman/listinfo/python-list


Easiest framework to develop simple interactive web site in python?

2011-09-12 Thread John Reid

Hi,

I need to write a web interface for some computational biology software 
I've written:

http://sysbio.mrc-bsu.cam.ac.uk/johns/STEME/rst/_build/html/index.html

I don't have much experience writing web sites or applications. Can 
anyone recommend a python framework that will allow me to easily write a 
few pages? I need to accept some user input in the form of some options 
and download a potentially large file from the user's computer. The job 
can take some time to run so I'll need to notify them via email when it 
has finished.


I should say our group already uses an Apache web server so I'd like to 
host the pages from that server.


I know there are various python web frameworks but I don't want to learn 
a complicated one, I really just want the simplest tool for the job. Are 
any of the following suitable?


Zope, Django, Pylons, Grok, Pyramid

I see quite a few are listed here:
http://wiki.python.org/moin/WebFrameworks

Thanks in advance for any help,
John.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Easiest framework to develop simple interactive web site in python?

2011-09-13 Thread John Reid

On 12/09/11 19:37, Stefaan Himpe wrote:

The simplest one to learn is web2py http://www.web2py.com
No configuration needed, just unpack and get started.
It also has very good documentation and tons of little examples to get
things done.

The other options you mentioned are good too :)



OK I've had a look at bottle, cherrypy and web2py and they look fairly 
straightforward. I'll check out some more and see where I get to. Thanks 
for the tips,

John.

--
http://mail.python.org/mailman/listinfo/python-list


Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid
Hi,

I was hoping namedtuples could be used as replacements for tuples in all 
instances. There seem to be some differences between how tuples and namedtuples 
are created. For example with a tuple I can do:

a=tuple([1,2,3])

with namedtuples I get a TypeError:

from collections import namedtuple
B=namedtuple('B', 'x y z')
b=B([1,2,3])

TypeError: __new__() takes exactly 4 arguments (2 given)
> (3)()
  1 from collections import namedtuple
  2 B=namedtuple('B', 'x y z')
> 3 b=B([1,2,3])

I'm seeing this problem because of the following code in IPython:

def canSequence(obj):
if isinstance(obj, (list, tuple)):
t = type(obj)
return t([can(i) for i in obj])
else:
return obj

where obj is a namedtuple and t([can(i) for i in obj]) fails with the 
TypeError. See http://article.gmane.org/gmane.comp.python.ipython.user/10270 
for more info.

Is this a problem with namedtuples, ipython or just a feature?

Thanks,
John.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid

On 18/02/13 12:05, Oscar Benjamin wrote:
> On 18 February 2013 12:03, Oscar Benjamin  wrote:
>> On 18 February 2013 11:47, John Reid  wrote:
>>> I'm seeing this problem because of the following code in IPython:
>>>
>>> def canSequence(obj):
>>> if isinstance(obj, (list, tuple)):
>>> t = type(obj)
>>> return t([can(i) for i in obj])
>>> else:
>>> return obj
>> What is the point of the code above? If obj is a list or a tuple you
>> create a new list or tuple with the same data and then return it
>> otherwise you just return the object. What about:
> Sorry, I didn't read this properly. I see that you want apply can() to
> all the elements. What is the reason for wanting to preserve the type
> of the sequence?
>
>
Well like I said it is not me that wants to do this. It is part of the
code in IPython for sending messages between clients and engines.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid
On 18/02/13 12:03, Oscar Benjamin wrote:
> On 18 February 2013 11:47, John Reid  wrote:
>> Hi,
>>
>> I was hoping namedtuples could be used as replacements for tuples in all 
>> instances.
> namedtuples are not really intended to serves as tuples anywhere. They
> are intended to provide lightweight, immutable, hashable objects with
> *named* (rather than numbered) values.
If they are not supposed to be tuples then calling them namedtuples and
inheriting from tuple seems a little odd.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid
On 18/02/13 12:11, Dave Angel wrote:
> On 02/18/2013 06:47 AM, John Reid wrote:
>> Hi,
>>
>> I was hoping namedtuples could be used as replacements for tuples in
>> all instances. There seem to be some differences between how tuples
>> and namedtuples are created. For example with a tuple I can do:
>>
>> a=tuple([1,2,3])
>>
>> with namedtuples I get a TypeError:
>>
>> from collections import namedtuple
>> B=namedtuple('B', 'x y z')
>> b=B([1,2,3])
> 
> You are passing a single list to the constructor, but you specified that
> the namedtuple was to have 3 items.  So you need two more.

I'm aware how to construct the namedtuple and the tuple. My point was
that they use different syntaxes for the same operation and this seems
to break ipython. I was wondering if this is a necessary design feature
or perhaps just an oversight on the part of the namedtuple author or
ipython developers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid

On 18/02/13 14:12, Oscar Benjamin wrote:
> On 18 February 2013 13:51, John Reid  wrote:
>> On 18/02/13 12:03, Oscar Benjamin wrote:
>>> On 18 February 2013 11:47, John Reid  wrote:
>>>> Hi,
>>>>
>>>> I was hoping namedtuples could be used as replacements for tuples in all 
>>>> instances.
>>> namedtuples are not really intended to serves as tuples anywhere. They
>>> are intended to provide lightweight, immutable, hashable objects with
>>> *named* (rather than numbered) values.
>> If they are not supposed to be tuples then calling them namedtuples and
>> inheriting from tuple seems a little odd.
> You can use namedtuple instances in places that expect tuples.
> Inheriting from tuples enables them to be all the things I said:
> lightweight, immutable and hashable. The type object itself has a
> different interface for the constructor, though.
>
>
Then I can't use them in every place I use tuples. For example IPython
relies upon the type's interface for the constructor as part of a
serialization mechanism.

I wonder why they have a different interface. It seems to restrict their
usability. No doubt there were other factors involved in the design of
the interface.

John.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid


On 18/02/13 14:15, Oscar Benjamin wrote:
> On 18 February 2013 14:09, John Reid  wrote:
>> On 18/02/13 12:11, Dave Angel wrote:
>>> On 02/18/2013 06:47 AM, John Reid wrote:
>>>> Hi,
>>>>
>>>> I was hoping namedtuples could be used as replacements for tuples in
>>>> all instances. There seem to be some differences between how tuples
>>>> and namedtuples are created. For example with a tuple I can do:
>>>>
>>>> a=tuple([1,2,3])
>>>>
>>>> with namedtuples I get a TypeError:
>>>>
>>>> from collections import namedtuple
>>>> B=namedtuple('B', 'x y z')
>>>> b=B([1,2,3])
>>>
>>> You are passing a single list to the constructor, but you specified that
>>> the namedtuple was to have 3 items.  So you need two more.
>>
>> I'm aware how to construct the namedtuple and the tuple. My point was
>> that they use different syntaxes for the same operation and this seems
>> to break ipython. I was wondering if this is a necessary design feature
>> or perhaps just an oversight on the part of the namedtuple author or
>> ipython developers.
> 
> I would say that depending on isinstance(obj, tuple) was the error. I
> can't offer a suggestion as you haven't clarified what the purpose of
> this code in canSequence() is or what constraints it is expected to
> satisfy.
> 

Like I said it is not my code. I'm hoping the IPython developers can
help me out here. That said it would be nice to know the rationale for
namedtuple.__new__ to have a different signature to tuple.__new__. I'm
guessing namedtuple._make has a similar interface to tuple.__new__. Does
anyone know what the rationale was for this design?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-18 Thread John Reid
On 18/02/13 14:53, Oscar Benjamin wrote:
> On 18 February 2013 14:23, John Reid  wrote:
> [snip]
>> That said it would be nice to know the rationale for
>> namedtuple.__new__ to have a different signature to tuple.__new__. I'm
>> guessing namedtuple._make has a similar interface to tuple.__new__. Does
>> anyone know what the rationale was for this design?
> 
> Because namedtuples use names for the arguments in the constructor:
> 
>>>> from collections import namedtuple
>>>> Point = namedtuple('Point', 'x y')
>>>> p1 = Point(x=2, y=3)
>>>> p1
> Point(x=2, y=3)
>>>> p1.x
> 2
> 
That's a good point. I haven't used __new__ much before but wouldn't
something like this __new__() cater for both uses? (Example taken from
namedtuple docs
http://docs.python.org/2/library/collections.html#collections.namedtuple).

>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
class Point(tuple):
'Point(x, y)'

__slots__ = ()

_fields = ('x', 'y')

def __new__(_cls, *args, **kwds):
'Create a new instance of Point(x, y)'
if args:
return _tuple.__new__(_cls, args)
else:
return _tuple.__new__(_cls, (kwds[f] for f in _fields))

...


Perhaps I could subclass namedtuple so that my namedtuples have the
correct signature for __new__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-19 Thread John Reid


On 19/02/13 00:18, Steven D'Aprano wrote:
> Terry Reedy wrote:
> 
>> On 2/18/2013 6:47 AM, John Reid wrote:
>>
>>> I was hoping namedtuples could be used as replacements for tuples
>>  >  in all instances.
>>
>> This is a mistake in the following two senses. First, tuple is a class
>> with instances while namedtuple is a class factory that produces
>> classes. (One could think of namedtuple as a metaclass, but it was not
>> implemented that way.) 
> 
> 
> I think you have misunderstood. I don't believe that John wants to use the
> namedtuple factory instead of tuple. He wants to use a namedtuple type
> instead of tuple.
> 
> That is, given:
> 
> Point3D = namedtuple('Point3D', 'x y z')
> 
> he wants to use a Point3D instead of a tuple. Since:
> 
> issubclass(Point3D, tuple) 
> 
> holds true, the Liskov Substitution Principle (LSP) tells us that anything
> that is true for a tuple should also be true for a Point3D. That is, given
> that instance x might be either a builtin tuple or a Point3D, all of the
> following hold:
> 
> - isinstance(x, tuple) returns True
> - len(x) returns the length of x
> - hash(x) returns the hash of x
> - x[i] returns item i of x, or raises IndexError
> - del x[i] raises TypeError
> - x + a_tuple returns a new tuple
> - x.count(y) returns the number of items equal to y
> 
> etc. Basically, any code expecting a tuple should continue to work if you
> pass it a Point3D instead (or any other namedtuple).
> 
> There is one conspicuous exception to this: the constructor:
> 
> type(x)(args)
> 
> behaves differently depending on whether x is a builtin tuple, or a Point3D.
> 

Exactly and thank you Steven for explaining it much more clearly.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Differences creating tuples and collections.namedtuples

2013-02-19 Thread John Reid


On 19/02/13 01:47, alex23 wrote:
> On Feb 18, 9:47 pm, John Reid  wrote:
>> See http://article.gmane.org/gmane.comp.python.ipython.user/10270 for more 
>> info.
> 
> One quick workaround would be to use a tuple where required and then
> coerce it back to Result when needed as such:
> 
> def sleep(secs):
> import os, time, parallel_helper
> start = time.time()
> time.sleep(secs)
> return tuple(parallel_helper.Result(os.getpid(), time.time() -
> start))
> 
> rc = parallel.Client()
> v = rc.load_balanced_view()
> async_result = v.map_async(sleep, range(3, 0, -1), ordered=False)
> for ar in async_result:
> print parallel_helper.Result(*ar)
> 
> You can of course skip the creation of Result in sleep and only turn
> it into one in the display loop, but it all depends on additional
> requirements (and adds some clarity to what is happening, I think).
> 

Thanks all I really need is a quick work around but it is always nice to
discuss these things. Also this class decorator seems to do the job for
ipython although it does change the construction syntax a little and is
probablty overkill. No doubt the readers of this list can improve it
somewhat as well.


import logging
_logger = logging.getLogger(__name__)
from collections import namedtuple

def make_ipython_friendly(namedtuple_class):
"""A class decorator to make namedtuples more ipython friendly.
"""
_logger.debug('Making %s ipython friendly.', namedtuple_class.__name__)

# Preserve original new to use if needed with keyword arguments
original_new = namedtuple_class.__new__

def __new__(cls, *args, **kwds):
_logger.debug('In decorator __new__, cls=%s', cls)
if args:
if kwds:
raise TypeError('Cannot construct %s from an positional
and keyword arguments.', namedtuple_class.__name__)
_logger.debug('Assuming construction from an iterable.')
return namedtuple_class._make(*args)
else:
_logger.debug('Assuming construction from keyword arguments.')
return original_new(namedtuple_class, **kwds)

namedtuple_class.__new__ = staticmethod(__new__) # set the class'
__new__ to the new one
del namedtuple_class.__getnewargs__ # get rid of getnewargs

return namedtuple_class

Result = make_ipython_friendly(namedtuple('Result', 'pid duration'))

-- 
http://mail.python.org/mailman/listinfo/python-list


Secure Postgres access

2006-09-06 Thread Reid Priedhorsky
Hi folks,

I would like to access a remote Postgres server from a Python program in a
secure way. Postgres doesn't currently listen to the Internet for
connections, and I'd prefer to keep it that way.

I know how to forward ports using SSH, but I don't like doing this because
then anyone who knows the port number can connect to Postgres over the
same tunnel. (I'm not the only user on the client machine.)

What I envision is something like wrapping an SSH connection which then
opens psql once connected, but I'm not too picky.

Both Postgres and the Python program are running on Linux.

Any ideas?

Thanks very much for any help.

Reid
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Secure Postgres access

2006-09-07 Thread Reid Priedhorsky
On Wed, 06 Sep 2006 09:29:59 -0700, Paul Rubin wrote:

> Reid Priedhorsky <[EMAIL PROTECTED]> writes:
>> I know how to forward ports using SSH, but I don't like doing this because
>> then anyone who knows the port number can connect to Postgres over the
>> same tunnel. (I'm not the only user on the client machine.)
> 
> Wouldn't they need a database password?

Well, right now, no. I have Postgres configured to trust the OS on who is
who. I would prefer not to change that because I don't want another place
containing authentication information. I'd like to connect by entering
only my SSH password, not my SSH password and a database password too.

This is why straight SSH tunneling, as suggested by Marshall and Larry,
isn't satisfactory: once I've set up the tunnel, anyone on the local
machine can connect to the tunnel and then they have passwordless access
into the database.

I control the database machine, and the only user is me. I don't control
the local machine, and it has many users I don't trust.

Thanks,

Reid

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Secure Postgres access

2006-09-09 Thread Reid Priedhorsky
On Thu, 07 Sep 2006 18:36:32 -0700, Paul Rubin wrote:

> Reid Priedhorsky <[EMAIL PROTECTED]> writes:
>> > Wouldn't they need a database password?
>> 
>> Well, right now, no. I have Postgres configured to trust the OS on who is
>> who. 
> 
> You trust the OS on the client machine, but not the client machine's
> users?  Does it run identd?  Maybe you could use that.  I'd consider
> this shaky for any real security application, but it might be better
> than nothing depending on what you're doing.

Hi Paul,

Thanks for your help.

No -- I suppose I wasn't clear. There are two machines involved:

A) Database server. Run by me. I trust the OS on who is who, and there is
only one user (me). So database clients run on this box don't require
a password.

B) Work machine. Run by others, many users. I'd like to also run my
database client (Python) here. SSH tunnel is unsatisfactory because other
folks can slip down the tunnel after I set it up and then connect to the
DB as me. Having the DB on (A) listen to the Internet as well as localhost
for connections is also unsatisfactory, because I don't want to set up
database passwords.

What I'd like is functionality similar to what Subversion does with
"svn+ssh://" URLs: an SSH tunnel that accepts only one connection and
doesn't have race conditions.

Thanks again,

Reid
-- 
http://mail.python.org/mailman/listinfo/python-list


A* search implementation in Python

2007-02-01 Thread Reid Priedhorsky
Hi folks,

I'm looking for an open-source Python implementation of A* search for use
in a mapping application.

As the star is an operator in Google, I haven't figured out how to
formulate a useful search. :/

Any help would be very much appreciated.

Reid
-- 
http://mail.python.org/mailman/listinfo/python-list


Forking SocketServer daemon -- updating state

2007-02-19 Thread Reid Priedhorsky
Hi folks,

I am implementing a forking SocketServer daemon that maintains significant
internal state (a graph that takes ~30s to build by fetching from a SQL
database, and eventually further state that may take up to an hour to
build).

I would like to be able to notify the daemon that it needs to update its
state. Because it forks for each new request, a request handler can't
update the state because then only the child would have the new state.

One idea I had was to use signals. Is it safe to write a signal handler
that does extensive work (several seconds)? Seems like even so, it might
be tricky to do this without race conditions.

Another possibility is that the signal handler simply sets a needs_update
flag, which I could check for in a handle_request() loop. The disadvantage
here is that the update wouldn't happen until after the next request is
handled, and I would like the state to be available for that next request.
A solution might be to send a signal followed by a dummy request, which
seems a bit awkward.

Any other ideas or suggestions?

Thanks in advance,

Reid

p.s. This group's help on A* search was very much appreciated -- just the
ticket!
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and windows bandwidth statistics?

2006-05-10 Thread Dave Reid
I've been searching for a something in Python for me to be able to get
the total outbound or inbound bandwidth (in Windows (or cross-OS
compatible). Can anyone help me out? Thanks!

-- 
http://mail.python.org/mailman/listinfo/python-list


python crash

2009-04-10 Thread John Reid
Python crashes in glibc with the following stack trace. I'm using an 
interface to R (rpy2), ipython, matplotlib, numpy, and scipy with a wx 
backend. I'm not sure if the stack trace shows which is the culprit. 
I've probably misconfigured one of their installs but knowing which one 
to recompile is a bit of a problem. They all took some time to install 
so I don't really want to start from scratch again and there's no 
knowing if that would fix it anyhow.


I'm on 64 bit Ubuntu:
Linux john-dell 2.6.27-11-generic #1 SMP Wed Apr 1 20:53:41 UTC 2009 
x86_64 GNU/Linux


Python 2.5.2
Numpy: 1.2.1
Scipy: 0.7.0rc2
IPython: 0.9.1
matplotlib: 0.98.5.2
wx: 2.8.8.0 (gtk2-unicode)

I suspect it is something to do with matplotlib as I think it happens 
when I'm plotting stuff but its not completely reproducible.


Also, I'm using the Ubuntu python package but I've built numpy, scipy 
and matplotlib myself. I didn't think this would be a problem though.


Any help appreciated.

Thanks,
John.



*** glibc detected *** /usr/bin/python2.5: free(): invalid pointer: 
0x7f6e499967a0 ***

=== Backtrace: =
/lib/libc.so.6[0x7f6e6dcf1a58]
/lib/libc.so.6(cfree+0x76)[0x7f6e6dcf40a6]
/usr/lib/python2.5/lib-dynload/readline.so[0x7f6e6aa7fcd0]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x57e2)[0x491052]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5[0x4dd4c2]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5[0x41fb08]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5(PyEval_CallObjectWithKeywords+0x72)[0x48a852]
/usr/bin/python2.5(PyInstance_New+0x86)[0x422956]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x3d12)[0x48f582]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x6872)[0x4920e2]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x6872)[0x4920e2]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x5483)[0x490cf3]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5[0x4dd4c2]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5[0x41fb08]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5(PyEval_CallObjectWithKeywords+0x72)[0x48a852]
/usr/bin/python2.5(PyInstance_New+0x86)[0x422956]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x3d12)[0x48f582]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x6872)[0x4920e2]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5(PyEval_EvalCode+0x32)[0x4929c2]
/usr/bin/python2.5(PyRun_FileExFlags+0x108)[0x4b2678]
/usr/bin/python2.5[0x489948]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x57e2)[0x491052]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x4cf8)[0x490568]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5[0x4dd4c2]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5[0x41fb08]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x3d12)[0x48f582]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x6872)[0x4920e2]
/usr/bin/python2.5(PyEval_EvalCodeEx+0x6ad)[0x4927cd]
/usr/bin/python2.5[0x4dd4c2]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5[0x41fb08]
/usr/bin/python2.5(PyObject_Call+0x13)[0x418c33]
/usr/bin/python2.5(PyEval_CallObjectWithKeywords+0x72)[0x48a852]
/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/_core_.so(_ZN12wxPyCallback12EventThunkerER7wxEvent+0x107)[0x7f6e662099d7]
/usr/lib/libwx_baseu-2.8.so.0(_ZN12wxEvtHandler21ProcessEventIfMatchesERK21wxEventTableEntryBasePS_R7wxEvent+0x89)[0x7f6e64556ca9]
/usr/lib/libwx_baseu-2.8.so.0(_ZN12wxEvtHandler23SearchDynamicEventTableER7wxEvent+0x54)[0x7f6e64556e54]
/usr/lib/libwx_baseu-2.8.so.0(_ZN12wxEvtHandler12ProcessEventER7wxEvent+0x92)[0x7f6e64557f42]
/usr/lib/libwx_gtk2u_core-2.8.so.0(_ZN11wxTimerBase6NotifyEv+0x66)[0x7f6e64ee51d6]
/usr/lib/libwx_gtk2u_core-2.8.so.0[0x7f6e64dec3cb]
/usr/lib/libglib-2.0.so.0[0x7f6e623a551b]
/usr/lib/libglib-2.0.so.0(g_main_context_dispatch+0x23b)[0x7f6e623a4d5b]
/usr/lib/libglib-2.0.so.0[0x7f6e623a852d]
/usr/lib/libglib-2.0.so.0(g_main_loop_run+0x1cd)[0x7f6e623a8a5d]
/usr/lib/libgtk-x11-2.0.so.0(gtk_main+0xa7)[0x7f6e63fb17a7]
/usr/lib/libwx_gtk2u_core-2.8.so.0(_ZN11wxEventLoop3RunEv+0x48)[0x7f6e64de3d18]
/usr/lib/libwx_gtk2u_core-2.8.so.0(_ZN9wxAppBase8MainLoopEv+0x4b)[0x7f6e64e6cf4b]
/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/_core_.so(_ZN7wxPyApp8MainLoopEv+0x37)[0x7f6e66208cd7]
/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/_core_.so[0x7f6e6626707e]
/usr/bin/python2.5(PyEval_EvalFrameEx+0x562b)[0x490e9b]
=== Memory map: 
0040-00525000 r-xp  08:05 4825998 
 /usr/bin/python2.5
00724000-00725000 r--p 00124000 08:05 4825998 
 /usr/bin/python2.5
00725000-00757000 rw-p 00125000 08:05 4825998 
 /usr/bin/python2.5

00757000-0075f000 rw-p 00757000 00:00 0
018e9000-0d5d6000 rw-p 018e9000 00:00 0 
 [

Re: Presentation software for Python code

2009-04-23 Thread John Reid

Michael Hoffman wrote:
Does anyone here have software they would suggest for making a 
presentation that includes Python code? Other than that it would 
probably be mainly bullet points. I'm willing to consider TeX- and 
HTML-based approaches.


I like pygments for formatting python code. It can generate TeX and you 
can use it inline it in your TeX source if you like.


--
http://mail.python.org/mailman/listinfo/python-list


Re: Presentation software for Python code

2009-04-23 Thread John Reid



Scott David Daniels wrote:

Michael Hoffman wrote:
You might take a look at Crunchy, and just do up your talk there.
Crunchy is a Python program that combines an otherwise static html
document with an interactive Python session within a browser
http://code.google.com/p/crunchy/


IPython offers something similar for giving demos. I've found that very 
useful in the past.


--
http://mail.python.org/mailman/listinfo/python-list


Re: Presentation software for Python code

2009-04-28 Thread John Reid



Neal Becker wrote:

IPython offers something similar for giving demos. I've found that very
useful in the past.


Really?  Any pointers?


http://ipython.scipy.org/doc/manual/html/api/generated/IPython.demo.html

--
http://mail.python.org/mailman/listinfo/python-list


Re: LaTeXing python programs

2009-05-20 Thread John Reid

Edward Grefenstette wrote:

I'm typing up my master's  thesis and will be including some of the
code used for my project in an appendix. The question is thus: is
there a LaTeX package out there that works well for presenting python
code?

verbatim is a bit ugly and doesn't wrap code, and while there are a
plethora of code colouring packages out there, they are not all easy
to use, so I thought I might ask what the popular options in the
community are.


pygments

--
http://mail.python.org/mailman/listinfo/python-list


Re: LaTeXing python programs

2009-05-20 Thread John Reid


Alan G Isaac wrote:

The listings package is great and highly configurable.
Note that you can also input entire files of Python code
or pieces of them based on markers.  Really quite great.


I tried listings. I believe pygments makes better formatted output (at 
least out of the box).


--
http://mail.python.org/mailman/listinfo/python-list


Re: LaTeXing python programs

2009-05-21 Thread John Reid



Edward Grefenstette wrote:

I'm trying to figure out how to use pygments. Are there any good usage
examples out there?


The documentation worked for me: http://pygments.org/docs/cmdline/

There is also a LaTeX package to call pygments at latex compilation time 
I forget what that is called though.


--
http://mail.python.org/mailman/listinfo/python-list


Safely updating master state in SocketServer with ForkingMixIn

2008-05-19 Thread Reid Priedhorsky
Dear all,

I have a TCP server written using SocketServer with ForkingMixIn.
Servicing connections is CPU-bound and can take several seconds.

I now need a way to safely tell the master process to update its state (by
groveling in a PostgreSQL database, potentially for several seconds). How
can I do this safely?

I thought of two ways:

1. Install a signal handler for SIGHUP and update state when that signal
is received.

2. Stop using ForkingMixIn and fork myself, except when "special" requests
come in requesting a state update, which don't fork.

3. Look for the existence of a file after each request, and if it's there
update state.

Option 2 seemed like it would require duplicating a lot of code from
ForkingMixIn, and Option 3 seems kind of lame, so I started down Option 1.
I produced the following code snippets:

   # main loop
   while True:
  server.handle_request()
  global update_required
  if (update_required):
 # update state
 update_required = False

   # signal handler
   def sighup(signum, frame):
  global update_required
  update_required = True

With this code, if the server is idle, SIGHUP causes it to immediately
drop out of handle_request() and execute the state updating block.

Do I have a race condition here? If the master process receives a SIGHUP
after a new connection starts but before a slave process is forked to
handle it, will that connection be messed up (to use highly technical
language)? Otherwise this technique seems compact and elegant.

Are there other options?

Your help would be much appreciated.

Thanks,

Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: scaling problems

2008-05-19 Thread Reid Priedhorsky
On Tue, 20 May 2008 10:47:50 +1000, James A. Donald wrote:
>
> 1.  Looks to me that python will not scale to very large programs,
> partly because of the lack of static typing, but mostly because there
> is no distinction between creating a new variable and utilizing an
> existing variable, so the interpreter fails to catch typos and name
> collisions.  I am inclined to suspect that when a successful small
> python program turns into a large python program, it rapidly reaches
> ninety percent complete, and remains ninety percent complete forever.

I find this frustrating too, but not to the extent that I choose a
different language. pylint helps but it's not as good as a nice, strict
compiler.

> 2.  It is not clear to me how a python web application scales.  Python
> is inherently single threaded, so one will need lots of python
> processes on lots of computers, with the database software handling
> parallel accesses to the same or related data.  One could organize it
> as one python program for each url, and one python process for each
> http request, but that involves a lot of overhead starting up and
> shutting down python processes.  Or one could organize it as one
> python program for each url, but if one gets a lot of http requests
> for one url, a small number of python processes will each sequentially
> handle a large number of those requests.  What I am really asking is:
> Are there python web frameworks that scale with hardware and how do
> they handle scaling?

This sounds like a good match for Apache with mod_python.

Reid
--
http://mail.python.org/mailman/listinfo/python-list


Validate XML against DTD and/or XML Schema?

2006-04-16 Thread Reid Priedhorsky
Hi folks,

I have a need to validate XML files against both DTDs and XML Schema from
the command line.

In an ideal world, I'd be able to do something like:

  $ python validate.py foo.xml

which would then parse and validate foo.xml using the schema or DTD
referenced within it.

What I'm looking for is the contents of validate.py. A Python solution
isn't essential, but I like Python and I'm doing some other light XML
stuff in Python, so I'd prefer it.

I did some Googling, but I'm a little overwhelmed by the quantity and
variety of stuff I found, and I found a lot of stuff that was out of date.
I thought it would be useful to ask here.

Let me know if you have any questions, and thanks very much for any help.

Reid
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The rap against "while True:" loops

2009-10-12 Thread John Reid

Mensanator wrote:

On Oct 12, 3:36�am, greg  wrote:

Mensanator wrote:

while not done:
� � ...
� � if n==1: done = True
� � ...

Seems to me that 'while not done:' is no better than
'while True:', because in both cases you have to look
inside the loop to find out what the exit condition
is.

Using a more meaningful name for the flag can help,
but you can't teach someone that just by giving them
an overly simplified rules such as "never use
while True:". They'll probably just replace it with
'while not done:' and think they've improved things,
without ever really understanding the issue.


You're missing the point. It's not that you have to
look inside for the terminating condition. It's that
you don't need a break.


Nothing wrong with a having a break IMHO.

while not done:

seems very dangerous to me as you'd have to

del done

before writing the same construct again. That's the sort of thing that 
leads to errors.


--
http://mail.python.org/mailman/listinfo/python-list


Re: The rap against "while True:" loops

2009-10-13 Thread John Reid



Mensanator wrote:

Nothing wrong with a having a break IMHO.


My opinion is that there is everything wrong with
having a break. I don't think I have ever used one,
I write code that doesn't depend on that crutch.
I guess its crutch-iness is in the eye of the beholder. You seem to have 
a dogmatic view about this.





while not done:

seems very dangerous to me as you'd have to

del done

before writing the same construct again. That's the sort of thing that
leads to errors.


Duh. I won't write silly code like that either.
If I need more than one loop structure then I'll
do something like

while not done_with_this


while not done_with_that

This is neither clean or well scoped.



Besides, since I _always_ initialize the flag
before entering a loop, the flag can be reused
and doesn't have to be deleted (as long as the
loops aren't nested). And since I don't use goto,
there's no chance the initialization can be avoided.
Initialising the flag is just another line of code that has to be 
interpreted later. I didn't notice the initialisation in your original post.




The best way to avoid the pitfalls of spaghetti
code is to not write it in the first place.

I agree. With 'break' it is obvious what the code does and there are 
fewer lines to write in the first place and comprehend in the second.


--
http://mail.python.org/mailman/listinfo/python-list


Re: The rap against "while True:" loops

2009-10-13 Thread John Reid



Mensanator wrote:

No, it's just that the OP was asking whether
avoiding "while True" is considered Best Practice.
How can you answer such a question without sounding
dogmatic?

I was just pointing out your style of programming seems inflexible.



"Just another line that has to be interpreted later"
is a strange comment in the context of "del done".
Interpreted in the sense that the maintainer of the code interprets it, 
not the machine.


--
http://mail.python.org/mailman/listinfo/python-list


Instance method decorator garbage collection problem

2010-06-23 Thread John Reid

Hi,

I've written a decorator that prints exceptions and I'm having some 
trouble with garbage collection.


My decorator is:

import sys
def print_exception_decorator(fn):
def decorator(self, *args, **kwds):
try:
return fn(*args, **kwds)
except:
print 'Exception:', sys.exc_info()
raise
return decorator



The class I want to decorate the methods of is:

class InstanceCounted(object):
"A class that keeps track of how many instances there are."
count = 0
def __init__(self):
InstanceCounted.count += 1
def __del__(self):
InstanceCounted.count -= 1

class A(InstanceCounted):
"A class that I want to decorate a method on."
def __init__(self):
super(A, self).__init__()
self.method = print_exception_decorator(self.method)

def __del__(self):
del self.method

def method(self):
pass



When I run the following it does not seem like my object 'a' is garbage 
collected:


print 'Have %d instances' % InstanceCounted.count
print 'Creating A'
a = A()
print 'Have %d instances' % InstanceCounted.count
print 'Deleting A'
del a
print 'Have %d instances' % InstanceCounted.count


This is the output:

Have 0 instances
Creating A
Have 1 instances
Deleting A
Have 1 instances


The InstanceCounted.count is 1 at the end. If I omit the call to 
"self.method = print_exception_decorator(self.method)" then the instance 
count goes down to 0 as desired. I thought that the decorator might be 
holding a reference to the instance through the bound method, so I added 
 the __del__() but it doesn't fix the problem.


Can anyone suggest anything? Is my technique to decorate bound methods 
not a good one? How else should I decorate a bound method?


Thanks in advance,
John.


--
http://mail.python.org/mailman/listinfo/python-list


Re: Instance method decorator garbage collection problem

2010-06-23 Thread John Reid



Thomas Jollans wrote:

The InstanceCounted.count is 1 at the end. If I omit the call to
"self.method = print_exception_decorator(self.method)" then the instance
count goes down to 0 as desired. I thought that the decorator might be
holding a reference to the instance through the bound method, so I added
 the __del__() but it doesn't fix the problem.


Adding __del__ like this does "fix the problem", but it introduces a new
one: lacking a call to super().__del__, you simply don't decrement the
instance count.


Now that's a good point! I've added super().__del__ but the problem 
remains for some reason. My A class now looks like:


class A(InstanceCounted):
"A class that I want to decorate a method on."
def __init__(self):
super(A, self).__init__()
self.method = print_exception_decorator(self.method)

def __del__(self):
super(A, self).__del__()
del self.method

def method(self):
pass


Did you try this?



To decorate a method, you'd best just decorate it normally. I doubt your
technique will work anyway, as the function returned by the decorator
isn't bound to the object, you'd need to pass one self reference
implicitly, which is then thrown away.


Looking at the original post, I had included an extra "self" in the 
argument list


def decorator(self, *args, **kwds):

should have been

def decorator(*args, **kwds):


With this correction my method decorates instance methods on objects 
successfully although I don't know why the garbage collection isn't working.






simply,

def exc_decor(fn):
@functools.wraps(fn)
def wrapper(*args, **keywords):
try:
return fn(*args, **keywords):
except:
#...
raise
return wrapper

class X(...):
   @exc_decor
   def foo(self, arg):
  pass

(if targeting pre-decorator Python, the code would look different of course)

This way, the function itself is decorated, and the function returned by
the decorator is bound to the object. It'll just work as expected, no
trickery required.


Thanks for this. I remember having some problems decorating instance 
methods in the past which is why I started doing it as in the original 
post. Your method seems just fine though.


Thanks,
John.

--
http://mail.python.org/mailman/listinfo/python-list


Check in interpreter if running a debug version of python

2010-07-27 Thread John Reid
Can I check in the interpreter if I am running a debug version of 
python? I don't mean if __debug__ is set, I want to know if python was 
compiled in debug mode.


Thanks,
John.

--
http://mail.python.org/mailman/listinfo/python-list


*** glibc detected *** gdb: malloc(): smallbin double linked list

2010-11-05 Thread John Reid

Hi,

I've compiled
Python 2.7 (r27:82500, Nov  2 2010, 09:00:37)
[GCC 4.4.3] on linux2

with the following configure options
./configure --prefix=/home/john/local/python-dbg --with-pydebug

I've installed numpy and some other packages but when I try to run my 
extension code under gdb I get the errors below. Does anyone have any 
ideas of how to track down what's happening here? I imagine I've 
misconfigured something somewhere. Is valgrind the answer?


Thanks,
John.



*** glibc detected *** gdb: malloc(): smallbin double linked list 
corrupted: 0x04de7ad0 ***

=== Backtrace: =
/lib/libc.so.6(+0x775b6)[0x7f0a252215b6]
/lib/libc.so.6(+0x7b8e9)[0x7f0a252258e9]
/lib/libc.so.6(__libc_malloc+0x6e)[0x7f0a2522658e]
gdb(xmalloc+0x18)[0x45bc38]
gdb[0x476df1]
gdb[0x474c9b]
gdb[0x474ee8]
gdb(execute_command+0x2dd)[0x458d1d]
gdb(catch_exception+0x50)[0x535510]
gdb[0x4b5191]
gdb(interp_exec+0x17)[0x535637]
gdb(mi_cmd_interpreter_exec+0x6c)[0x4b9adc]
gdb[0x4ba71a]
gdb(catch_exception+0x50)[0x535510]
gdb(mi_execute_command+0x97)[0x4ba137]
gdb[0x53a0f8]
gdb(gdb_do_one_event+0x29a)[0x53b38a]
gdb(catch_errors+0x5b)[0x53531b]
gdb(start_event_loop+0x1e)[0x53a90e]
gdb[0x44f619]
gdb(catch_errors+0x5b)[0x53531b]
gdb[0x450166]
gdb(catch_errors+0x5b)[0x53531b]
gdb(gdb_main+0x24)[0x44f554]
gdb(main+0x2e)[0x44f51e]
/lib/libc.so.6(__libc_start_main+0xfd)[0x7f0a251c8c4d]
gdb[0x44f429]
=== Memory map: 
0040-00818000 r-xp  08:05 4832730  /usr/bin/gdb
00a17000-00a18000 r--p 00417000 08:05 4832730  /usr/bin/gdb
00a18000-00a25000 rw-p 00418000 08:05 4832730  /usr/bin/gdb
00a25000-00a43000 rw-p  00:00 0
0287f000-0b92 rw-p  00:00 0  [heap]
7f0a1c00-7f0a1c021000 rw-p  00:00 0
7f0a1c021000-7f0a2000 ---p  00:00 0
7f0a20fc-7f0a20fd6000 r-xp  08:05 3498245  /lib/libgcc_s.so.1
7f0a20fd6000-7f0a211d5000 ---p 00016000 08:05 3498245  /lib/libgcc_s.so.1
7f0a211d5000-7f0a211d6000 r--p 00015000 08:05 3498245  /lib/libgcc_s.so.1
7f0a211d6000-7f0a211d7000 rw-p 00016000 08:05 3498245  /lib/libgcc_s.so.1
7f0a211fd000-7f0a21211000 r--p 000dc000 08:05 4825848 
/usr/lib/libstdc++.so.6.0.13
7f0a21211000-7f0a21218000 r--p 00018000 08:05 4841756 
/usr/lib/debug/lib/librt-2.11.1.so
7f0a21218000-7f0a21226000 r--p 1000 08:05 4841756 
/usr/lib/debug/lib/librt-2.11.1.so

7f0a21226000-7f0a2123e000 r--p 000bc000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a2123e000-7f0a21287000 r--p 003dd000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a21287000-7f0a21299000 r--p 00425000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a21299000-7f0a213e7000 r--p 0018c000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a213e7000-7f0a2152f000 r--p 0207c000 08:05 4653324 
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so
7f0a2152f000-7f0a22027000 r--p 01585000 08:05 4653324 
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so

7f0a22027000-7f0a2240 rw-p  00:00 0
7f0a22408000-7f0a224d1000 r--p 00315000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a224d1000-7f0a224ff000 r--p 002e8000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a224ff000-7f0a22526000 r--p 00038000 08:05 4653310
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/myrrh_pylib-d
7f0a22526000-7f0a2259c000 r--p 0151 08:05 4653324 
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so
7f0a2259c000-7f0a2280c000 r--p 012a 08:05 4653324 
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so

7f0a2280c000-7f0a2343f000 rw-p  00:00 0
7f0a23443000-7f0a2344c000 r--p 0001a000 08:05 6169643 
/home/john/local/python-dbg/lib/python2.7/lib-dynload/datetime.so

7f0a2344c000-7f0a2345c000 r--p 002d9000 08:05 4653290
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_python.so.1.44.0
7f0a2345c000-7f0a23461000 r--p 0005e000 08:05 4653310
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/myrrh_pylib-d
7f0a23461000-7f0a23477000 r--p 0001f000 08:05 4653310
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/myrrh_pylib-d
7f0a23477000-7f0a2347d000 r--p 4000 08:05 4653095
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/libboost_system.so.1.44.0
7f0a2347d000-7f0a2350c000 r--p 00757000 08:05 4653324 
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so
7f0a2350c000-7f0a23555000 r--p 021c3000 08:05 4653324 
/home/john/Dev/MyProjects/Bio/MotifSearch/python/stempy/_debug/_stempy.so
7f0a23555000-7f0a2355b000 r--p 00048000 08:05 6169627 
/home/john/local/python-dbg/lib/python2.7/lib-dynload/_ct

Re: web hosting, first hand experiences?

2011-07-03 Thread Alan Harris-Reid


On 19:59, Daniel Fetchinson wrote:

Hi folks, I know this comes up regularly but the thing is that the
quality of service changes also quite regularly with many of the
hosting companies. What's currently the best option for shared hosting
of a turbogears application? I'm thinking of dreamhost and webfaction
does anyone have any recent experiences with these two? Or others?

Cheers,
Daniel



Hi Daniel,

I can wholeheartedly recommend WebFaction.  I currently have an account 
running 3 different CherryPy applications (so TurboGears shouldn't pose 
any problems), and apart from initial teething problems, they have been 
running for months without interruption.  As well as an excellent 
control panel, they give you full Linux command-line access to your 
site(s).  The level of support is as good as you will get anywhere 
(short of having experts with you in the office!), and they know a huge 
amount about Python web applications.  Nothing seems to be too much 
trouble for them.  They also provide a 60-day money-back guarantee, so 
you can try-before-you-buy.


Best wishes,
Alan Harris-Reid


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py to exe converter

2011-03-21 Thread Alan Harris-Reid

On 19:59, PATRICIA MEDINA wrote:
I know there is a converter for python 2.x to executable file, but is 
there one for python 3.x yet?


I use cx_Freeze without any problems  (//cx-freeze.sourceforge.net/)

HTH
Alan


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py to exe converter

2011-03-21 Thread Alan Harris-Reid
According to //sourceforge.net/projects/py2exe/files/, the latest 
version only goes as far as Python2.5 :-(


Alan


On 21/03/2011 19:47, Santoso Wijaya wrote:

There's also py2exe: http://www..py2exe.org/ <http://www.py2exe.org/>

~/santa


On Mon, Mar 21, 2011 at 11:06 AM, Alan Harris-Reid 
mailto:a...@baselinedata.co.uk>> wrote:


On 19:59, PATRICIA MEDINA wrote:

I know there is a converter for python 2.x to executable file,
but is there one for python 3.x yet?


I use cx_Freeze without any problems 
(//cx-freeze.sourceforge.net/ <http://cx-freeze.sourceforge.net/>)


HTH
Alan



--
http://mail.python.org/mailman/listinfo/python-list






No virus found in this message.
Checked by AVG - www.avg.com <http://www.avg.com>
Version: 10.0.1204 / Virus Database: 1498/3520 - Release Date: 03/21/11



-- 
http://mail.python.org/mailman/listinfo/python-list


Sys.path entries

2009-12-30 Thread Alan Harris-Reid


Hi there,

In my sys.path (interpreter only, no application loaded), I have the 
following strange entries...
'C:\\WINDOWS\\system32\\python31.zip'.  This file does not exist 
anywhere (although python31.dll does exist in \windows\system32\), where 
could it have come from?
'C:\\program files\\python31\\lib\\plat-win'.  There is no such 
directory, although I can see that this has been added by the PYTHONPATH 
varible in PyConfig.h (when is this loaded?)


Is there any way of removing these entries, or are they best left where 
they are?  (I am using Python 3.1 on WinXP)


Also, regarding PyConfig.h - is this read every time I start Python.exe?

Many thanks,
Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: Sys.path entries

2009-12-31 Thread Alan Harris-Reid

Marco Salden wrote:

On Dec 30, 8:13 pm, Alan Harris-Reid  wrote:
  

Hi there,

In my sys.path (interpreter only, no application loaded), I have the
following strange entries...
'C:\\WINDOWS\\system32\\python31.zip'.  This file does not exist
anywhere (although python31.dll does exist in \windows\system32\), where
could it have come from?
'C:\\program files\\python31\\lib\\plat-win'.  There is no such
directory, although I can see that this has been added by the PYTHONPATH
varible in PyConfig.h (when is this loaded?)

Is there any way of removing these entries, or are they best left where
they are?  (I am using Python 3.1 on WinXP)

Also, regarding PyConfig.h - is this read every time I start Python.exe?

Many thanks,
Alan Harris-Reid



Hi Alan,

Same for me: C:\Windows\system32\python25.zip is in the only non-"C:
\Python25" directroy&file in my sys.path (under Python 2.5).
No idea why it needs it. And also in my case the zip file isnt in that
location anyway. So also not 3K only or so.
But I have no issues with it (so far :-)), do you? Do you run into
problems because of this in the path?

HTH,
Marco


Hi Marco,thanks for the reply,

No, it doesn't cause any problems.  I just thought it would be nice to 
have a 'clean' path environment as possible.


Regards,
Alan



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sys.path entries

2009-12-31 Thread Alan Harris-Reid

Gabriel Genellina wrote:
En Thu, 31 Dec 2009 04:31:06 -0300, Marco 
Salden  escribió:



On Dec 30, 8:13 pm, Alan Harris-Reid  wrote:

Hi there,

In my sys.path (interpreter only, no application loaded), I have the
following strange entries...
'C:\\WINDOWS\\system32\\python31.zip'.  This file does not exist
anywhere (although python31.dll does exist in \windows\system32\), 
where

could it have come from?
'C:\\program files\\python31\\lib\\plat-win'.  There is no such
directory, although I can see that this has been added by the 
PYTHONPATH

varible in PyConfig.h (when is this loaded?)

Is there any way of removing these entries, or are they best left where
they are?  (I am using Python 3.1 on WinXP)



Same for me: C:\Windows\system32\python25.zip is in the only non-"C:
\Python25" directroy&file in my sys.path (under Python 2.5).
No idea why it needs it. And also in my case the zip file isnt in that
location anyway. So also not 3K only or so.
But I have no issues with it (so far :-)), do you? Do you run into
problems because of this in the path?


Don't worry. The pythonNN.zip entry in sys.path is required to allow a 
complete Python install to reside in a .zip file -- all modules used 
at start time (os, ntpath, site...) must be importable before user 
code has a chance of altering the import mechanisms. Tools like py2exe 
may take advantage of that. See PEP 273: 
http://www.python.org/dev/peps/pep-0273/
Normally, such zip file doesn't exist, and Python just ignores its 
sys.path entry; look at sys.path_importer_cache:


py> sys.path_importer_cache
...
 'C:\\WINDOWS\\system32\\python26.zip': 0x00AB0028>,
 'd:\\apps\\python26\\lib\\plat-win': 0x00AB0480>,

 'd:\\apps\\python26\\lib\\site-packages': None,
...

Same for the plat-win directory; someone *could* use it for 
Windows-specific stuff, but it doesn't exist by default and is simply 
ignored.


Also, regarding PyConfig.h - is this read every time I start 
Python.exe?


No. It's a copy of the .h file used when Python was compiled from its 
C sources. distutils may read it to gather some information. Unless 
you compile the interpreter from source yourself, it serves no other 
purpose than document the options originally used to compile it.


Thanks for the reply Gabriel.  All useful stuff to store in my 
(ever-fading) brain.


Regards
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Dynamic HTML controls

2010-01-11 Thread Alan Harris-Reid


Hi,

Does anyone know where I can find any decent dynamically-constructed 
HTML control classes (dropdown list, table, input field, checkbox, etc.) 
written in Python.  For example, for a HTML table I would like something 
like...


MyTable = html_table()   # instantiate class
MyTable.data = data_list# data-list (eg. cursor from SQL SELECT 
statement)
MyTable.border = 1  
MyTable.width = 987  
MyTable.column_headers = col_headers# list or tuple of column-headers 
table_code = MyTable.table.create()   # returns string 
containing appropriate HTML code


I don't mind writing my own classes (it will be good practice for me), 
but I don't want to re-invent the wheel if it can be avoided.



TIA,
Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic HTML controls

2010-01-12 Thread Alan Harris-Reid

alex23 wrote:

On Jan 12, 1:26 pm, Alan Harris-Reid 
wrote:
  

Does anyone know where I can find any decent dynamically-constructed
HTML control classes (dropdown list, table, input field, checkbox, etc.)
written in Python.



There's pyWeb[1], which seems pretty close to what you're asking for:

  mytable =able(align='center', cellspacing=0, cellpadding=3,
border=
  mytable.add(tr(td("first row"), td("second row")))

While it might be a little heavier than what you're after, you should
also be able to do this with ToscaWidgets[2]. You'd probably have to
make basic widgets for the general HTML controls, but that would give
you a good head-start on writing your own, more complex widgets.
Widgets can be a compilation of Python, HTML, CSS & JS. (I used this
fairly extensively when it used to be called TurboWidgets)

If you want to roll your own from scratch, I'm a big fan of the html
[3] library:

  >>> from html import HTML
  >>> h =TML()
  >>> with h.table(border=', width='987'):
  ...   with h.tr:
  ... for header in ['column 1', 'column 2']:
  ...   h.th(header)
  ...
  >>> print h
  
  column 1column 2
  

1: http://www.freenet.org.nz/python/pyweb
2: http://toscawidgets.org
3: http://pypi.python.org/pypi/html/1.7

Hi Alex (I'm assuming that is your name from your nickname)

Thanks for the reply - I'll check-out all 3 solutions you suggest and 
I'm sure I'll find something near to what I am looking for.


Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic HTML controls

2010-01-14 Thread Alan Harris-Reid


Pierre Quentel wrote:

On 12 jan, 04:26, Alan Harris-Reid  wrote:
  

Hi,

Does anyone know where I can find any decent dynamically-constructed
HTML control classes (dropdown list, table, input field, checkbox, etc.)
written in Python.  For example, for a HTML table I would like something
like...

MyTable =tml_table()   # instantiate class
MyTable.data =ata_list# data-list (eg. cursor from SQL SELECT
statement)
MyTable.border =  
MyTable.width =87  
MyTable.column_headers =ol_headers# list or tuple of column-headers

table_code =yTable.table.create()   # returns string
containing appropriate HTML code

I don't mind writing my own classes (it will be good practice for me),
but I don't want to re-invent the wheel if it can be avoided.

TIA,
Alan Harris-Reid



Hi,

There are a few modules to generate HTML from Python : there is a list
at http://wiki.python.org/moin/Templating, section HTML Generation
packages

With HTMLTags, your example would be coded like this :

from HTMLTags import *
table =ABLE(border=1,width~7)
table <=R(Sum([TD(header) for header in col_headers]))
for result in data_list:
table <=R(Sum([TD(value) for value in result]))
print table

The operator <=eans "add child" in the DOM tree structure, it avoids
having to nest tags with brackets

- Pierre


Thanks Pierre.  I can see this module being very useful.  I have 
downloaded the code from the Activestate site (is that the latest 
version?) and will try it out as soon as possible.

Is HTMLTags Python3 compatible? (I am using 3.1).

Regards,
Alan Harris-Reid

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic HTML controls

2010-01-21 Thread Alan Harris-Reid

Aahz wrote:

In article ,
Alan Harris-Reid   wrote:
  
Does anyone know where I can find any decent dynamically-constructed 
HTML control classes (dropdown list, table, input field, checkbox, etc.) 
written in Python.  For example, for a HTML table I would like something 
like...



You might look at Quixote:
http://quixote.ca/
  

Thanks for that Aahz - I'll check it out.

Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python 3's adoption

2010-01-26 Thread Alan Harris-Reid

Xah Lee wrote:

Some thoughts about Python 3 Adoption.

Xah Lee, 2010-01-26

Some notes of Wikipedia readings related to Python.

Unladen Swallow, a new project from Google. It is a new python
compiler with the goal of 5 times faster than the de facto standand
implementation CPython. Also note Stackless Python, which is already
been used in some major commercial projects.

Was looking into what's new in Python 3. See: 
http://docs.python.org/dev/3.0/whatsnew/3.0.html.
>From a quick reading, i don't really like it. Here's some highlights:

* Print is now a function. Great, much improvement.
* Many functions that return lists now returns “Views” or
“Iterators” Instead. A fucking fuck all fucked up shit. A extraneous
“oop engineering” complication. (See: Lambda in Python 3000)
* The cmp() function used in sort is basically gone, users are now
supposed to use the “key” parameter instead. This is a flying-face-
fuck to computer science. This would be the most serious fuckup in
python 3. (See: Sorting in Python and Perl)
* Integers by default is long. Great!
* Much more integrated unicode support, rewrite of most its text
or string semantics. Fantastic. Finally.

Am looking because i wonder if i should switch to python 3 for my own
few scripts, and rewrite my Python Tutorial for version 3. Am also
interested to know how python 3 is received by the computing industry.
Apparantly, a little search on the web indicates that vast majority of
python base have not switched, as expected, for many good reasons.
Vast majority of major python modules and tools have not switched.
Most linux distro have not switched, i don't find any large
corporation having adopted Python 3 (Google, Yahoo, Facebook,
NASA,... ). (sources: Source, Source) Basically, such a incompatible
change with trivial, ideological improvements, is too costy to switch.

I wonder, if by 2015, will most large corporate users have switched to
python 3. I give it a maybe. In today's Proliferation of Computing
Languages, such a major antic by Guido can just hurt itself. What is
he thinking? He of course thought himself as a god of lang designer,
who sincerely wants to push towards perfection, all future-looking.
Unfortunately, the tens of other major language designers all think
similarly.

perm archive of this post with possible updates here:
http://xahlee.org/comp/python3.html

Any comment on this?

  Xah
? http://xahlee.org/

Hello Xah,

I have no figures to base this on (just what I have read on the web), 
but although the vast majority of comanies with big Python investments 
are probably waiting for the 'critical mass' to use Python3 regularly 
(oil-tanker effect), I would like to think that smaller operations are 
experimenting with it more-and-more.


I think that for beginners who have dived into Python in the last 6-12 
months (like me), it doesn't make sense to start with an older version. 
I do not want to learn 'old' syntax and functions of a language, only to 
have to learn the new versions when most developers upgrade to 3 - I 
might as well learn the new syntax now and be ahead-of-the-game ;-) . I 
know my choice of related packages (web-framework, ORM, 
templating-engine) is very limited at present, but there are enough 
branches and beta-versions around to help me with my learning-curve, and 
I figure there will be some full-production-releases around by the time 
I am 'fluent' with Python (12-18 months?).


Currently I am using Python 3.1 and CherryPy (3.20 rc1) every day, and 
have had no serious problems (yet).


I would be interested to hear how other people are using Python 3, and 
with what compatible packages.


Regards,
Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Threading issue with SQLite

2010-01-29 Thread Alan Harris-Reid

Hi,

I am creating a web application (using Python 3.1 and CherryPy 3.2) 
where a SQLite connection and cursor object are created using the 
following code (simplified from the original):


class MainSite:
   con = sqlite.connect('MyDatabase.db')
   cursor = con.cursor()

   def index_page():
  some HTML code
  cursor.execute(some SQL statement)
  more HTML code
 
   def another_page():

  some HTML code
  cursor.execute(anotherSQL statement)
  more HTML code

When I call a URL which launches the another_page() method I get the 
error message "sqlite3.ProgrammingError: SQLite objects created in a 
thread can only be used in that same thread."


Questions...
1.  Is there a large overhead in opening a new SQLite connection for 
each thread (ie. within each method)?
2.  Is there any way to use the same connection for the whole class (or 
should I forget that idea completely?)
3.  When a method returns to the calling method, is the connection 
automatically closed (assuming the object is local, of course) or does 
it have to be done explicitly using connection.close()?


TIA,
Alan Harris-Reid

--
http://mail.python.org/mailman/listinfo/python-list


Web development with Python 3.1

2009-10-25 Thread Alan Harris-Reid


I am very much new to Python, and one of my first projects is a simple
data-based website. I am starting with Python 3.1 (I can hear many of 
you shouting "don't - start with 2.6"), but as far as I can see, none of 
the popular python-to-web frameworks (Django, CherryPy, web.py, etc.) 
are Python3 compatible yet.


So, what can I use to start my web programming experience using 3.1?

Any help would be appreciated.

Alan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-26 Thread Alan Harris-Reid

Exarkun - thanks for the reply

> don't - start with 2.6
Thought you might say that ;-)

Regards,
Alan

On 25 Oct, 11:52 pm, a...@baselinedata.co.uk wrote:


I am very much new to Python, and one of my first projects is a simple
data-based website. I am starting with Python 3.1 (I can hear many of 
you shouting "don't - start with 2.6"), but as far as I can see, none 
of the popular python-to-web frameworks (Django, CherryPy, web.py, 
etc.) are Python3 compatible yet.


So, what can I use to start my web programming experience using 3.1?

Any help would be appreciated.


don't - start with 2.6

Alan

--
http://mail.python.org/mailman/listinfo/python-list



No virus found in this incoming message.
Checked by AVG - www.avg.com 
Version: 8.5.423 / Virus Database: 270.14.31/2458 - Release Date: 10/25/09 
08:10:00

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-26 Thread Alan Harris-Reid




Anyway, for simple web programming, frameworks are not worth the
hassle.  Just use the cgi module.


I can vouch for what Paul says. I started in Python 3 years ago, and I 
did so with a web application (still working on it!). I'm using the 
cgi approach, and it certainly teaches you the concepts. I fail to see 
how starting with a framework is a good idea if you don't know how the 
frameworks work (or what they're actually doing). It would be a bit 
like doing a web page in Dreamw***er and thinking you understand 
HTML/CSS.


B

Hi Brendon, thanks for the advice.  Looks like I'll have to go the cgi 
route myself if I want to stick with with Python3.


Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-26 Thread Alan Harris-Reid


Hi Paul, thanks for the reply (despite the sarcasm ;-) ),

>Does it occur to you that the unavailability of those frameworks is 
part of the REASON they say to use 2.x?
Of course, but that doesn't mean that there isn't someone out there who 
may know of a framework that is already Python3 compatible, or is being 
worked-on.


>Have you answered your own question?
No

>Anyway, for simple web programming, frameworks are not worth the 
hassle. Just use the cgi module.

Ok - I'll look into it.

>... you are the one who decided to zoom off into the 3.1 wilderness 
before the framework developers got there.
I haven't zoomed-off anywhere yet - in fact I've hardly started.  I made 
the decision to start with 3.1 based on the fact that it was the latest 
version, and hoping that there may be some framework stuff out there 
(because 3.0 has been out for a while now).  However, it looks as though 
I might have to review that decision, but what I've learned so far is 
pretty simple stuff, so it won't be wasted.


Regards,
Alan

Alan Harris-Reid  writes:
  

I am very much new to Python, and one of my first projects is a simple
data-based website. I am starting with Python 3.1 (I can hear many of
you shouting "don't - start with 2.6"), but as far as I can see, none
of the popular python-to-web frameworks (Django, CherryPy, web.py,
etc.) are Python3 compatible yet.

So, what can I use to start my web programming experience using 3.1?



Does it occur to you that the unavailability of those frameworks is
part of the REASON they say to use 2.x?  Have you answered your own
question?

Anyway, for simple web programming, frameworks are not worth the
hassle.  Just use the cgi module.

If you want to use a framework, well, you are the one who decided to
zoom off into the 3.1 wilderness before the framework developers got
there.  If you're an experienced programmer in other languages and
you're determined to use a framework, maybe a worthwhile Python
learning project would be to help port your favorite framework to 3.1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-27 Thread Alan Harris-Reid

Aaron Watters wrote:

On Oct 25, 7:52 pm, Alan Harris-Reid  wrote:
  

I am very much new to Python, and one of my first projects is a simple
data-based website. I am starting with Python 3.1 (I can hear many of
you shouting "don't - start with 2.6"), but as far as I can see, none of
the popular python-to-web frameworks (Django, CherryPy, web.py, etc.)
are Python3 compatible yet.

So, what can I use to start my web programming experience using 3.1?

Any help would be appreciated.

Alan



Don't. use python 2.6 with WHIFF :)
  http://aaron.oirt.rutgers.edu/myapp/GenBankTree/index
  http://whiff.sourceforge.net

-- Aaron Watters

Thanks for the advice

Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Web development with Python 3.1

2009-10-28 Thread Alan Harris-Reid

John Nagle wrote:

Alan Harris-Reid wrote:

I am very much new to Python, and one of my first projects is a simple
data-based website. I am starting with Python 3.1 


   Until MySQLdb gets ported to something later than Python 2.5, support
for a "data-based web site" probably has to be in Python 2.5 or earlier.

   The C module situation for Python 3.x still isn't very good.
Realistically, the production version of Python is 2.5.  This process
is taking long enough that I'm worried that Python 3.x could do for
Python what Perl 6 did for Perl - provide an upgrade path that nobody
takes.

   HTMLTemplate 
("http://py-templates.sourceforge.net/htmltemplate/index.html";)
is a minimal templating system for fill-in-the-blanks template work in 
Python.

Actually, if you have HTMLTemplate, FCGI, and MySQLdb, you have enough to
do a back-end database.

   There are some advantages to libraries (you call them) over 
"frameworks"

(they call you) if you're doing something unusual.  Frameworks are more
useful if you're doing yet another "Web 2.0" web site.

John Nagle





Thanks for the advice John.  I am concerned at what you say about the 
uptake of 3.x - you could be right (although I hope you eventually 
turn-out to be wrong :-) ).


Regards
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-10-28 Thread Alan Harris-Reid


Martin v. Löwis wrote:

I am very much new to Python, and one of my first projects is a simple
data-based website. I am starting with Python 3.1 (I can hear many of
you shouting "don't - start with 2.6"), but as far as I can see, none of
the popular python-to-web frameworks (Django, CherryPy, web.py, etc.)
are Python3 compatible yet.



That's not entirely true, see

http://wiki.python.org/moin/PortingDjangoTo3k

Regards,
Martin
  


Interesting link.  Thanks for the info.

Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web development with Python 3.1

2009-11-07 Thread Alan Harris-Reid


mario ruggier wrote:

With respect to to original question regarding web frameworks +
database and Python 3, all the following have been available for
Python 3 since the day Python 3.0 was released:

QP, a Web Framework
http://pypi.python.org/pypi/qp/

Durus, a Python Object Database (the "default" in qp, for user
sessions, etc)
http://pypi.python.org/pypi/Durus/

Evoque, state-of-the-art templating engine
http://pypi.python.org/pypi/evoque/
(this one is available for py3.0 since a little later, 21-jan-2009)

All the above also runs on python 2.4 (thru to python 3)

For the record, you may see the list of all pypi packages availabe for
Python 3 at:
http://pypi.python.org/pypi?:action=browse&show=all&c=533

m.

Thanks for those links Mario - I'll check them out asap..

Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


String prefix question

2009-11-08 Thread Alan Harris-Reid
In the Python.org 3.1 documentation (section 20.4.6), there is a simple 
“Hello World” WSGI application which includes the following method...


def hello_world_app(environ, start_response):
status = b'200 OK' # HTTP Status
headers = [(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers
start_response(status, headers)

# The returned object is going to be printed
return [b"Hello World"]

Question - Can anyone tell me why the 'b' prefix is present before each 
string? The method seems to work equally well with and without the 
prefix. From what I can gather from the documentation the b prefix 
represents a bytes literal, but can anyone explain (in simple english) 
what this means?


Many thanks,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: String prefix question

2009-11-09 Thread Alan Harris-Reid


Gerard Flanagan wrote:

Alan Harris-Reid wrote:
In the Python.org 3.1 documentation (section 20.4.6), there is a 
simple “Hello World” WSGI application which includes the following 
method...


def hello_world_app(environ, start_response):
status ='200 OK' # HTTP Status
headers =(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers
start_response(status, headers)

# The returned object is going to be printed
return [b"Hello World"]

Question - Can anyone tell me why the 'b' prefix is present before 
each string? The method seems to work equally well with and without 
the prefix. From what I can gather from the documentation the b 
prefix represents a bytes literal, but can anyone explain (in simple 
english) what this means?


Many thanks,
Alan


Another link:

http://www.stereoplex.com/two-voices/python-unicode-and-unicodedecodeerror 








Gerard - thanks for the link - explains it well.

Many thanks,
Alan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: String prefix question

2009-11-09 Thread Alan Harris-Reid


Benjamin Kaplan wrote:

On Sun, Nov 8, 2009 at 9:38 PM, Alan Harris-Reid
 wrote:
  

In the Python.org 3.1 documentation (section 20.4.6), there is a simple
"Hello World" WSGI application which includes the following method...

def hello_world_app(environ, start_response):
status ='200 OK' # HTTP Status
headers =(b'Content-type', b'text/plain; charset=utf-8')] # HTTP Headers
start_response(status, headers)

# The returned object is going to be printed
return [b"Hello World"]

Question - Can anyone tell me why the 'b' prefix is present before each
string? The method seems to work equally well with and without the prefix.
From what I can gather from the documentation the b prefix represents a
bytes literal, but can anyone explain (in simple english) what this means?

Many thanks,
Alan



The rather long version:
read http://www.joelonsoftware.com/articles/Unicode.html

A somewhat shorter summary, along with how Python deals with this:

Once upon a time, someone decided to allocate 1 byte for each
character. Since everything the Americans who made the computers
needed fit into 7 bits, this was alright. And they called this the
American Standard Code for Information Interchange (ASCII). When
computers came along, device manufacturers realized that they had 128
characters that didn't mean anything, so they all made their own
characters to show for the upper 128. And when they started selling
computers internationally, they used the upper 128 to store the
characters they needed for the local language. This had several
problems.

1) Files made by on one computer in one country wouldn't display right
in a computer made by a different manufacturer or for a different
country

2) The 256 characters were enough for most Western languages, but
Chinese and Japanese need a whole lot more.

To solve this problem, Unicode was created. Rather than thinking of
each character as a distinct set of bits, it just assigns a number to
each one (a code point). The bottom 128 characters are the original
ASCII set, and everything else you could think of was added on top of
that - other alphabets, mathematical symbols, music notes, cuneiform,
dominos, mah jong tiles, and more. Unicode is harder to implement than
a simple byte array, but it means strings are universal- every program
will interpret them exactly the same. Unicode strings in python are
the default ('') in Python 3.x and created in 2.x by putting a u in
front of the string declaration (u'')

Unicode, however, is a concept, and concepts can't be mapped to bits
that can be sent through the network or stored on the hard drive. So
instead we deal with strings internally as Unicode and then give them
an encoding when we send them back out. Some encodings, such as UTF-8,
can have multiple bytes per character and, as such, can deal with the
full range of Unicode characters. Other times, programs still expect
the old 8-bit encodings like ISO-8859-1 or the Windows Ansi code
pages. In Python, to declare that the string is a literal set of bytes
and the program should not try and interpret it, you use b'' in Python
3.x, or just declare it normally in Python 2.x ('').

--
What happens in your program:

When you print a Unicode string, Python has to decide what encoding to
use. If you're printing to a terminal, Python looks for the terminal's
encoding and uses that. In the event that it doesn't know what
encoding to use, Python defaults to ASCII because that's compatible
with almost everything. Since the string you're sending to the web
page only contains ASCII characters, the automatic conversion works
fine if you don't specify the b''. Since the resulting page uses UTF-8
(which you declare in the header), which is compatible with ASCII, the
output looks fine. If you try sending a string that has non-ASCII
characters, the program might throw a UnicodeEncodeError because it
doesn't know what bytes to use for those characters. It may be able to
guess, but since I haven't used WSGI directly before, I can't say for
sure.
  


Thanks Benjamin - great 'history' lesson - explains it well.

Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading issue with SQLite

2010-02-02 Thread Alan Harris-Reid


Many thanks to all who replied to my questions re. SQLite connections, 
cursors and threading.


Looks like I have got some reading to do regarding connection pooling and
a decent SQLite ORM package.  Does anyone know of any which are Python 3 
compatible?


Many thanks,
Alanj
--
http://mail.python.org/mailman/listinfo/python-list


Passing parameters in URL

2010-02-03 Thread Alan Harris-Reid
I have a web-page where each row in a grid has edit/delete buttons to 
enable the user to maintain a selected record on another page.  The 
buttons are in the form of a link with href='/item_edit?id=123', but 
this string appears in the URL and gives clues as to how to bypass the 
correct sequence of events, and could be risky if they entered the URL 
directly (especially when it comes to deleting records).


Is there another way of passing a record-id to a method
a) without it appearing in the URL?
b) without the user being able to fathom-out how to attach which id to 
which URL?


As each link contains row-id, I guess there is nothing to stop someone 
from getting the id from the page source-code.  Is it safe to use the 
above href method if I test for authorised credentials (user/password 
stored as session variables, perhaps?) before performing the edit/delete 
action?


I am currently using CherryPy 3.2, but I guess the theory could apply to 
any HTTP framework or web app..


Any help would be appreciated.  
Alan Harris-Reid


--
http://mail.python.org/mailman/listinfo/python-list


Re: Passing parameters in URL

2010-02-04 Thread Alan Harris-Reid
Many thanks to all those who replied to my question and clearing-up the 
differences between GET and POST.  I think I know what to do now - if 
not, I'll be back :-)


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Editor for Python

2010-02-05 Thread Alan Harris-Reid


Hi Laszlo,

I use Wing IDE (not free, $35 for personal edition) and PyScripter 
(free).  I find both good, for different reasons.


Regards,
Alan



Laszlo Nagy wrote:


  Hi All,

I know that this question was put up on this list a thousand times. I 
know that most of the editors are listed here: 
http://wiki.python.org/moin/PythonEditors


I already tried most of them. But still, I need something that is not 
listed there. Requirements:


* starts and works fast
* has code folding, displays identation guides
* auto completion
* class browser
* source code browser (e.g. a list of definitions, when you click
  it jumps to the definition
* integration with pychecker or pylint
* UTF-8 files
* free, or not-so-expensive
* works on linux and windows

The one I'm using now is Geany. It does everything, except class 
browser and pychecker/pylint. Now maybe, I can install (or write??) a 
geany extension that would allow me to use pychecker. But I could not 
find information on that. There where others I tried (PyPE, DrPython, 
KomodoEdit, Editra etc.) but all of them failed for some reason. Can 
you please suggest another editor that I could try? Or send me a link 
that tells how to write or install pychecked plugin for Geany.


Thanks,

   Laszlo



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: DreamPie - The Python shell you've always dreamed about!

2010-02-23 Thread Alan Harris-Reid

gorauskas wrote:

I installed it on a Windows 7 machine with CPython 2.6.4 and I get the
following error:

Traceback (most recent call last):
  File "dreampie.py", line 3, in 
  File "dreampielib\gui\__init__.pyc", line 73, in 
  File "dreampielib\gui\load_pygtk.pyc", line 49, in load_pygtk
ImportError: DLL load failed: The specified module could not be found.

What am I doing wrong?

Thanks,  JGG
And I installed it on WinXP sp3 and Python 3.1 - when launched a window 
flashes before my eyes, then disappears!  Has the installation package 
been checked for all common Windows versions?


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: DreamPie - The Python shell you've always dreamed about!

2010-02-23 Thread Alan Harris-Reid

Chris Colbert wrote:
Do you have gtk and PyGTK installed? Sounds like a missing dependency 
to me.


On Tue, Feb 23, 2010 at 6:56 AM, Alan Harris-Reid 
mailto:aharrisr...@googlemail.com>> wrote:


gorauskas wrote:

I installed it on a Windows 7 machine with CPython 2.6.4 and I
get the
following error:

Traceback (most recent call last):
 File "dreampie.py", line 3, in 
 File "dreampielib\gui\__init__.pyc", line 73, in 
 File "dreampielib\gui\load_pygtk.pyc", line 49, in load_pygtk
ImportError: DLL load failed: The specified module could not
be found.

What am I doing wrong?

Thanks,  JGG

And I installed it on WinXP sp3 and Python 3.1 - when launched a
window flashes before my eyes, then disappears!  Has the
installation package been checked for all common Windows versions?

Regards,
Alan

-- 
http://mail.python.org/mailman/listinfo/python-list




Hi Chris, thanks for the reply,

That explains it.  No, I don't have gtk installed - I wasn't aware of 
that dependency.


Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Super() function

2010-03-24 Thread Alan Harris-Reid

Hi,

Using Python 3.1, I sometimes use the super() function to call the 
equivalent method from a parent class, for example


def mymethod(self):
   super().mymethod()
   some more code...

Is there any way of writing the code so that the super() call is generic 
and automatically recognises the name of the current method (ie. 
something like super().thismethod()) or do I always have to repeat the 
method name after super()?


TIA,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Super() function

2010-03-27 Thread Alan Harris-Reid

³p wrote:

Hi:
 
On 25 March 2010 11:17, Alan Harris-Reid <mailto:aharrisr...@googlemail.com>> wrote:


Hi,

Using Python 3.1, I sometimes use the super() function to call the
equivalent method from a parent class, for example

def mymethod(self):
  super().mymethod()
  some more code...

Is there any way of writing the code so that the super() call is
generic and automatically recognises the name of the current
method (ie. something like super().thismethod()) or do I always
have to repeat the method name after super()?

TIA,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list





   I think, the super() method is designed to delegate any method call 
to one of the class in its mro list, and the super() function its self 
return a 'super' object, so it is better to write what method you want 
to delegate, maybe it's not the current method. 


--
Best wishes from Ray ...

Thanks Ray - I'll stick to repeating the method name.

Regards,
Alan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Super() function

2010-03-27 Thread Alan Harris-Reid

Gabriel Genellina wrote:
En Thu, 25 Mar 2010 00:17:52 -0300, Alan 
Harris-Reid  escribió:


Using Python 3.1, I sometimes use the super() function to call the 
equivalent method from a parent class, for example


def mymethod(self):
super().mymethod()
some more code...

Is there any way of writing the code so that the super() call is 
generic and automatically recognises the name of the current method 
(ie. something like super().thismethod()) or do I always have to 
repeat the method name after super()?


This recipe does what you want:
http://code.activestate.com/recipes/286195-selfsuper/
(but requires a bit of black magic...)


Hi Gabriel - thanks for the reply.

Goodness me - that's a mighty complicated recipe for what I want to 
achieve!  I think I'll stick with repeating the method name - it's a 
small price to pay.


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


SQLite date fields

2010-11-24 Thread Alan Harris-Reid


Hi,

I am having design problems with date storage/retrieval using Python and 
SQLite.


I understand that a SQLite date column stores dates as text in ISO 
format (ie. '2010-05-25').  So when I display a British date (eg. on a 
web-page) I convert the date using 
datetime.datetime.strptime(mydate,'%Y-%m-%d').strftime('%d/%m/%Y').


However, when it comes to writing-back data to the table, SQLite is very 
forgiving and is quite happy to store '25/06/2003' in a date field, but 
this is not ideal because a) I could be left with a mixture of date 
formats in the same column,  b) SQLite's date functions only work with 
ISO format.
Therefore I need to convert the date string back to ISO format before 
committing, but then I would need a generic function which checks data 
about to be written in all date fields and converts to ISO if 
necessary.  That sounds a bit tedious to me, but maybe it is inevitable.


Are there simpler solutions?  Would it be easier to change the date 
field to a 10-character field and store 'dd/mm/' throughout the 
table?  This way no conversion is required when reading or writing from 
the table, and I could use datetime() functions if I needed to perform 
any date-arithmetic.


How have other developers overcome this problem?  Any help would be 
appreciated.  For the record, I am using SQLite3 with Python 3.1.


Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQLite date fields

2010-11-26 Thread Alan Harris-Reid
To all those who have replied on this thread - many thanks.  It looks as 
though I've got to look further into date objects, SQLite's native date 
functions, detect_types, etc..


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Framework design question

2010-12-05 Thread Alan Harris-Reid


Hi,

When committing data that has originally come from a webpage, sometimes 
data has to be converted to a data type or format which is suitable for 
the back-end database.  For instance, a date in 'dd/mm/' format 
needs to be converted to a Python date-object or '-mm-dd' in order 
to be stored in a SQLite date column (SQLite will accept 'dd/mm/yy', but 
that can cause problems when data is retrieved).


Question - at what point should the data be converted?
a) As part of a generic web_page_save() method (immediately after 
data validation, but before a row.table_update() method is called).
b) As part of row.table_update() (a data-object method called from 
web- or non-web-based applications, and includes construction of a 
field-value parameter list prior to executing the UPDATE command).


In other words, from a framework point-of-view, does the data-conversion 
belong to page-object processing or data-object processing?


Any opinions would be appreciated.

Alan
--
http://mail.python.org/mailman/listinfo/python-list


Career path - where next?

2011-01-12 Thread Alan Harris-Reid


Hi there, I wonder if any Python folk out there can help me.

For many years I was a contractor developing desktop and web 
applications using Visual Foxpro as my main language, with Foxpro, 
SQL-server and Oracle as back-end databases.  Unfortunately Foxpro was 
killed-off by Microsoft, hence my work dried-up and my last 'big' 
contract ended about a year ago.  Since then I have taken time off 
programming doing house-renovation, and in the last 6 months I have been 
updating my programming skills by learning Python (3) with SQLite, 
JavaScript, HTML and CSS to a level where I can create and deploy 
data-based web-sites.


My situation now is that I am reasonably comfortable with the above 
languages and am now in a position where I wish to return to employment 
using my new and/or existing skills (contract/permanent, full/part-time 
or teleworking).   However, I have yet to find any UK vacancy which will 
accept a relative 'beginner' - they all require at least 2-3 years 
Python in a commercial environment.  It's a catch-22 situation - it's 
hard to get a job without experience, but you need a job to get 
experience in the 1st place!


I would even consider doing small projects for nothing so that I can 
'get my foot in the door' (although I hope to be wise-enough to know 
when I am being taken advantage of!).  I am also mailing CVs to agencies 
I think may be interested.


If anyone out has ideas as to how to proceed towards achieving my goal, 
I would be grateful for any advice.


Regards,
Alan Harris-Reid

--
http://mail.python.org/mailman/listinfo/python-list


Re: Career path - where next?

2011-01-15 Thread Alan Harris-Reid
To all those who answered my original post so far (Jon Clements, Terry 
Jan Reedy, Philip Semanchuk) - many thanks.  Your suggestions have given 
me a number of avenues to follow.  I'll let you know how I get on.


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Career path - where next?

2011-01-17 Thread Alan Harris-Reid


Hi Fred, thanks for the reply.

I have already contacted old clients (those that are still in business), 
but unfortunately they have either gone the 'off the shelf' route (ie. 
don't use bespoke software any more), or moved-over to .NET, which is a 
route which I don't want to follow.  Still, at least I've let them know 
what I am doing now and you never know where word-of-mouth may lead.  I 
tried C# for a while, but after Foxpro it appeared to me to be such a 
horrible, clunky language.  Then I discovered Python about a year ago 
and have loved it ever since.


Regards,
Alan


On 17/01/2011 16:13, Sells, Fred wrote:

Since you were burned by Microsoft dropping foxpro, I suspect many
others were also.  I would contact all my old clients and see how they
are coping and tell them you've been converting FoxPro to *xyz* and can
help them (assuming of course that you have done some of this).  If they
don't have anything, ask them for leads contacts.

Trying to get a job "cold" is much more difficult than if you have a
referral.


-- 
http://mail.python.org/mailman/listinfo/python-list


Code redundancy

2010-04-20 Thread Alan Harris-Reid

Hi,

During my Python (3.1) programming I often find myself having to repeat 
code such as...


class1.attr1 = 1
class1.attr2 = 2
class1.attr3 = 3
class1.attr4 = 4
etc.

Is there any way to achieve the same result without having to repeat the 
class1 prefix?  Before Python my previous main language was Visual 
Foxpro, which had the syntax...


with class1
  .attr1 = 1
  .attr2 = 2
  .attr3 = 3
  .attr4 = 4
  etc.
endwith

Is there any equivalent to this in Python?

Any help would be appreciated.

Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Jean-Michel Pichavant wrote:

Alan Harris-Reid wrote:

Hi,

During my Python (3.1) programming I often find myself having to 
repeat code such as...


class1.attr1 = 1
class1.attr2 = 2
class1.attr3 = 3
class1.attr4 = 4
etc.

Is there any way to achieve the same result without having to repeat 
the class1 prefix?  Before Python my previous main language was 
Visual Foxpro, which had the syntax...


with class1
  .attr1 = 1
  .attr2 = 2
  .attr3 = 3
  .attr4 = 4
  etc.
endwith

Is there any equivalent to this in Python?

Any help would be appreciated.

Alan Harris-Reid

Hello,

Use an effective text editor, repeating stuff should not be a problem. 
In a more general manner, avoid trying to speed your writing while you 
should care speeding the reading.
Most of the tricks you could use will confuse the reader (unless the 
reader is familiar with Visual foxpro).


Anyway,

for attrName, value in [
   ('attr1', 1),
   ('attr2', 2),
   ('attr3', 3),
   ]:
   setattr(class1, attrName, value)

or

class Foo:
   def __init__(self):
  self.attr1=None
  self.attr2=None
  self.attr3=None

   def set(self, *args, **kwargs):
  for k in kwargs:
 if hasattr(self, k):
 setattr(self, k, kwargs[k])
 else:
   raise AttributeError('%s instance has no attribute "%s"' % 
(self.__class__.__name__, k))


f = Foo()
f.set(attr1=25)
print f.__dict__
f.set(attr3=4, attr2=89)
print f.__dict__
f.set(bar= 8)

output:
{'attr2': None, 'attr3': None, 'attr1': 25}
{'attr2': 89, 'attr3': 4, 'attr1': 25}
AttributeError: Foo instance has no attribute "bar"


JM


Hi Jean-Michel,

Interesting solutions, but I think for the effort involved (and 
readability) I'll stick to repeating the class.


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Peter Otten wrote:

Alan Harris-Reid wrote:

  

Hi,

During my Python (3.1) programming I often find myself having to repeat
code such as...

class1.attr1 = 1
class1.attr2 = 2
class1.attr3 = 3
class1.attr4 = 4
etc.

Is there any way to achieve the same result without having to repeat the
class1 prefix?  Before Python my previous main language was Visual
Foxpro, which had the syntax...

with class1
   .attr1 = 1
   .attr2 = 2
   .attr3 = 3
   .attr4 = 4
   etc.
endwith

Is there any equivalent to this in Python?



No. You could write a helper function

  

def update(obj, **kw):


... for k, v in kw.items():
... setattr(obj, k, v)
...

and then use keyword arguments:

  

class A: pass


...
  

a = A()
update(a, foo=42, bar="yadda")
a.foo, a.bar


(42, 'yadda')
  

But if you are doing that a lot and if the attributes are as uniform as 
their names suggest you should rather use a Python dict than a custom class.


  

d = {}
d.update(foo=42, bar="whatever")
d


{'foo': 42, 'bar': 'whatever'}
  

d["bar"]


'whatever'

Peter

Hi Peter, thanks for the reply,

Interesting solution, but it looks as though it may be easier to repeat 
the class prefix a few times.


Alan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Iain King wrote:

On Apr 20, 2:43 pm, Alan Harris-Reid 
wrote:
  

Hi,

During my Python (3.1) programming I often find myself having to repeat
code such as...

class1.attr1 =
class1.attr2 =
class1.attr3 =
class1.attr4 =
etc.

Is there any way to achieve the same result without having to repeat the
class1 prefix?  Before Python my previous main language was Visual
Foxpro, which had the syntax...

with class1
   .attr1 =
   .attr2 =
   .attr3 =
   .attr4 =
   etc.
endwith

Is there any equivalent to this in Python?

Any help would be appreciated.

Alan Harris-Reid



The pythonic equivalent of VB 'with' is to assign to a short variable
name, for example '_':

_ =lass1
_.attr1 =
_.attr2 =
_.attr3 =
_.attr4 =

alternatively, you could use the __setattr__ method:

for attr, value in (
('attr1', 1),
('attr2', 2),
('attr3', 3),
('attr4', 4)):
class1.__setattr__(attr, value)

and to get a bit crunchy, with this your specific example can be
written:

for i in xrange(1, 5):
class1.__setattr__('attr%d' % i, i)

Iain

Hi Iain, thanks for the reply,

Like the _. prefix idea - I didn't know _ could be used as a variable name.


for i in xrange(1, 5):
   class1.__setattr__('attr%d' % i, i)



Good solution if the values matched the attribute names, but 
unfortunately they don't.  That was just a (bad) example to illustrate 
my problem.


Regards,
Alan




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Stefan Behnel wrote:

Alan Harris-Reid, 20.04.2010 15:43:

During my Python (3.1) programming I often find myself having to repeat
code such as...

class1.attr1 = 1
class1.attr2 = 2
class1.attr3 = 3
class1.attr4 = 4
etc.

Is there any way to achieve the same result without having to repeat the
class1 prefix? Before Python my previous main language was Visual
Foxpro, which had the syntax...

with class1
.attr1 = 1
.attr2 = 2
.attr3 = 3
.attr4 = 4
etc.
endwith

Is there any equivalent to this in Python?


There's more than one way to do this, depending on your actual needs 
and the source of the attributes. I assume this is done in __init__?


This might work for you:

self.__dict__.update(attr1=1, attr2=2, attr3=3, attr4=4)

You should also think once more about the use of the code you 
presented above, having to set all those attributes may have a little 
smell. Maybe that's totally ok, but since you mention that you "often" 
find yourself doing the above, you may also have a mental design 
problem somewhere. We can't tell unless you provide a more concrete 
example than what you show above.


Stefan

Hi Stefan, thanks for the reply.

The code is not usually in class.__init__ (otherwise I would have used 
the self. prefix), but I like your self.__dict__.update(...) solution 
and I'll try and remember it.


The code I was thinking of goes something like as follows (don't have a 
specific example to hand, but the principal is the same)...


NewClass = BaseClass()
NewClass.attr1 = value1
NewClass.attr2 = value2
NewClass.attr3 = value3
etc.

So if there are more than a couple of attributes to set for a class 
instance, how would you approach it (short of passing the values as 
parameters to BaseClass)?


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Xavier Ho wrote:
On Wed, Apr 21, 2010 at 7:59 AM, Alan Harris-Reid 
mailto:aharrisr...@googlemail.com>> wrote:


The code is not usually in class.__init__ (otherwise I would have
used the self. prefix)


Alan, if your variables are not usually in __init__, what's preventing 
you from using class variables like this:


>>> class Test():
... something = 1
... more = 2
...
>>> Test.more

2

What's your use case?

Cheers,
Xav

Hi Xavier, thanks for the reply,

In this case I am setting attributes of an instantiated class, so the 
original class might go something like


class Test
   attr1 = some default value
   attr2 = another default value
   attr3 = yet another default value
   etc.

and the instantiated class might go something like

Test2 = Test()
Test2.attr1 = runtime value
Test2.attr2 = another runtime value
etc.

Regards,
Alan




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Chris Rebert wrote:

On Tue, Apr 20, 2010 at 2:59 PM, Alan Harris-Reid
 wrote:
  

Stefan Behnel wrote:


Alan Harris-Reid, 20.04.2010 15:43:
  

During my Python (3.1) programming I often find myself having to repeat
code such as...

class1.attr1 = 1
class1.attr2 = 2
class1.attr3 = 3
class1.attr4 = 4
etc.

Is there any way to achieve the same result without having to repeat the
class1 prefix? Before Python my previous main language was Visual
Foxpro, which had the syntax...

with class1
.attr1 = 1
.attr2 = 2
.attr3 = 3
.attr4 = 4
etc.
endwith

Is there any equivalent to this in Python?


There's more than one way to do this, depending on your actual needs and
the source of the attributes. I assume this is done in __init__?

This might work for you:

   self.__dict__.update(attr1=1, attr2=2, attr3=3, attr4=4)

You should also think once more about the use of the code you presented
above, having to set all those attributes may have a little smell. Maybe
that's totally ok, but since you mention that you "often" find yourself
doing the above, you may also have a mental design problem somewhere. We
can't tell unless you provide a more concrete example than what you show
above.

Stefan
  

Hi Stefan, thanks for the reply.

The code is not usually in class.__init__ (otherwise I would have used the
self. prefix), but I like your self.__dict__.update(...) solution and I'll
try and remember it.

The code I was thinking of goes something like as follows (don't have a
specific example to hand, but the principal is the same)...

NewClass = BaseClass()
NewClass.attr1 = value1
NewClass.attr2 = value2
NewClass.attr3 = value3
etc.

So if there are more than a couple of attributes to set for a class
instance, how would you approach it (short of passing the values as
parameters to BaseClass)?



Why are you against passing them as parameters?
If your constructor would have a lot of parameters, it may be a sign that:
(A) you have some Data Clumps
(http://martinfowler.com/bliki/DataClump.html) among the parameters
that ought to be made into full objects
(B) your class is doing too many things and needs to be split into
multiple classes
(http://www.refactoring.com/catalog/extractClass.html)

Cheers,
Chris
--
Yay Refactoring!
http://blog.rebertia.com


Hi Chris, thanks for the reply.

Nothing against passing the values as parameters, but it can start to 
look a bit ugly if there are too many of them.  Which brings me to your 
2nd point of maybe refactoring the passing/receiving of parameters so 
that I can use an object with attributes instead of individual variable 
values.


Thanks,
Alan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code redundancy

2010-04-20 Thread Alan Harris-Reid

Ethan Furman wrote:

Alan Harris-Reid wrote:
The code is not usually in class.__init__ (otherwise I would have 
used the self. prefix), but I like your self.__dict__.update(...) 
solution and I'll try and remember it.


The code I was thinking of goes something like as follows (don't have 
a specific example to hand, but the principal is the same)...


NewClass = BaseClass()
NewClass.attr1 = value1
NewClass.attr2 = value2
NewClass.attr3 = value3
etc.

So if there are more than a couple of attributes to set for a class 
instance, how would you approach it (short of passing the values as 
parameters to BaseClass)?


Unless I'm missing something (your use-case, perhaps? ;) in this 
example NewClass is *not* a class -- it's an instance of BaseClass, 
and you are dynamically adding attributes to it.


It's definitely a switch coming from FoxPro (me, too!), but it is well 
worth it once your brain starts working pythonically.


~Ethan~


Hi Ethan,
You are correct - NewClass is an instance of BaseClass and I chose a 
very bad class-name as an example.


Good to see ex-Fox people on this list.  I have recently got stuck-into 
learning Python after my last VFP contract finished last December - wish 
I had started years ago.  Really glad I went for Python, which I thought 
would be the easiest transition from Foxpro (I looked at other 
languages, but none came near to Python in terms of popularity and 
developer-friendly syntax).  What's your story?


Regards,
Alan

--
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Code redundancy

2010-04-21 Thread Alan Harris-Reid

Andreas Löscher wrote:

You can do something like this:

  

class A(): pass
inst=)
exec("""


... a=
... b=2
... c=3
... d=4
... """) in inst.__dict__
  

 inst.a


1
  


This executes the Statement in the exec function and uses inst.__dict__
as namespace. But be aware, that this is not recommended. If you mess
with __dict__, you won't be able to replace it with some logic
(parameter) if you need to do something more than setting a variable.

Best

Hi Andreas, thanks for the reply,

Looks like I'll be sticking with repeating the class-name for a while.

Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code redundancy

2010-04-21 Thread Alan Harris-Reid

Ryan Kelly wrote:

On Tue, 2010-04-20 at 14:43 +0100, Alan Harris-Reid wrote:
  

Hi,

During my Python (3.1) programming I often find myself having to repeat 
code such as...


class1.attr1 = 1
class1.attr2 = 2
class1.attr3 = 3
class1.attr4 = 4
etc.

Is there any way to achieve the same result without having to repeat the 
class1 prefix?  Before Python my previous main language was Visual 
Foxpro, which had the syntax...


with class1
   .attr1 = 1
   .attr2 = 2
   .attr3 = 3
   .attr4 = 4
   etc.
endwith

Is there any equivalent to this in Python?




Please don't take this as in invitation to disregard the excellent
advice already received in this thread - I just want to point out that
python can usually be bent to your will.  Observe:

  
  from withhacks import namespace


  with namespace(class1):
  attr1 = 1
  attr2 = 2


This will do pretty much what you get from the "with" statement in
javascript (I assume it's similar to Visual Foxpro).


But don't use this in any real code.  Seriously, don't even think about
it.  You don't want to know the kind of abuses that go on under the
covers to make this kind of syntax hacking work...



  Cheers,

 Ryan

Hi Ryan, thanks for that.

No - I will not be adopting that solution.  Is there anything Python 
can't do if you bend the rules far enough?  ;-)


Regards,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Email attachment problem

2010-04-29 Thread Alan Harris-Reid

Hi there,

I want to send an email with an attachment using the following code 
(running under Python 3.1, greatly simplified to show example)


   from email.mime.multipart import MIMEMultipart
   from email.mime.text import MIMEText

   msg = MIMEMultipart()
   msg['From'] = from_addr
   msg['To'] = to_addr
   msg['Subject'] = subject
   msg.attach(MIMEText(body))

   fp = open(att_file)
   att_msg = MIMEText(fp.read())
   attachment = att_msg.add_header('Content-Disposition', 'attachment', 
filename=att_file)

   msg.attach(attachment)

   # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail()
   send_string = msg.as_string()


The attachment object msg1 returns 'email.mime.text.MIMEText' object at 
', but when the att_msg.add_header(...) line runs the result is 
None, hence the program falls-over in msg.as_string() because no part of 
the attachment can have a None value.  (Traceback shows "'NoneType' 
object has no attribute 'get_content_maintype'" in line 118 of _dispatch 
in generator.py, many levels down from msg.as_string())


Has anyone any idea what the cause of the problem might be?  Any help 
would be appreciated.


Alan Harris-Reid
--
http://mail.python.org/mailman/listinfo/python-list


Re: Email attachment problem

2010-04-29 Thread Alan Harris-Reid

Chris Rebert wrote:

On Thu, Apr 29, 2010 at 1:06 PM, Alan Harris-Reid
 wrote:
  

Hi there,

I want to send an email with an attachment using the following code (running
under Python 3.1, greatly simplified to show example)

  from email.mime.multipart import MIMEMultipart
  from email.mime.text import MIMEText

  msg = MIMEMultipart()
  msg['From'] = from_addr
  msg['To'] = to_addr
  msg['Subject'] = subject
  msg.attach(MIMEText(body))

  fp = open(att_file)
  att_msg = MIMEText(fp.read())
  attachment = att_msg.add_header('Content-Disposition', 'attachment',
filename=att_file)
  msg.attach(attachment)

  # set string to be sent as 3rd parameter to smptlib.SMTP.sendmail()
  send_string = msg.as_string()


The attachment object msg1 returns 'email.mime.text.MIMEText' object at
', but when the att_msg.add_header(...) line runs the result is
None, hence the program falls-over in msg.as_string() because no part of the
attachment can have a None value.  (Traceback shows "'NoneType' object has
no attribute 'get_content_maintype'" in line 118 of _dispatch in
generator.py, many levels down from msg.as_string())

Has anyone any idea what the cause of the problem might be?  Any help would
be appreciated.



.add_header() modifies the MIMEText object *in-place*; per Python
conventions, mutator methods return None; hence, attachment = None.

Try instead (untested):
att_msg.add_header('Content-Disposition', 'attachment', filename=att_file)
msg.attach(att_msg)

Cheers,
Chris
--
http://blog.rebertia.com

Hi Chris,

You are right - that does the trick.

Many thanks,
Alan

-- 
http://mail.python.org/mailman/listinfo/python-list


Binary file email attachment problem

2010-05-09 Thread Alan Harris-Reid

Hi there,

Using Python 3.1.2 I am having a problem sending binary attachment files 
(jpeg, pdf, etc.) - MIMEText attachments work fine. The code in question 
is as follows...


for file in self.attachments:
  part = MIMEBase('application', "octet-stream")
  part.set_payload(open(file,"rb").read())
  encoders.encode_base64(part)
  part.add_header('Content-Disposition', 'attachment; filename="%s"' % 
file)

  msg.attach(part)   # msg is an instance of MIMEMultipart()

server = smtplib.SMTP(host, port)
server.login(username, password)
server.sendmail(from_addr, all_recipients, msg.as_string())

However, way down in the calling-stack (see traceback below), it looks 
as though msg.as_string() has received an attachment which creates a 
payload of 'bytes' type instead of string.  I suspect the error lies in 
the encoding somewhere, but I've no idea where.  I have also tried 
MIMEApplication and MIMEImage, but the error still remains.  I have seen 
many similar code examples on the web, all of which fail for me, so I 
wonder if there is something wrong with my environment.


Has anyone any idea what might be causing the problem? Any help would be 
appreciated.


Alan



builtins.TypeError: string payload expected: 
File "c:\Dev\CommonPY\Scripts\email_send.py", line 147, in send
 server.sendmail(self.from_addr, all_recipients, msg.as_string())
File "c:\Program Files\Python31\Lib\email\message.py", line 136, in 
as_string

 g.flatten(self, unixfrom=unixfrom)
File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten
 self._write(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write
 self._dispatch(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in 
_dispatch

 meth(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 181, in 
_handle_multipart

 g.flatten(part, unixfrom=False)
File "c:\Program Files\Python31\Lib\email\generator.py", line 76, in flatten
 self._write(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 101, in _write
 self._dispatch(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 127, in 
_dispatch

 meth(msg)
File "c:\Program Files\Python31\Lib\email\generator.py", line 155, in 
_handle_text

 raise TypeError('string payload expected: %s' % type(payload))



--
http://mail.python.org/mailman/listinfo/python-list


Removing anti-Jewish postings from Python list

2010-06-16 Thread Alan Harris-Reid
Any idea how we get rid of this 'noise'?  Will it eventually go away if 
we ignore it, or is there anything the moderators can do to clean-up 
this (normally) wonderful resource for Python programmers?


Regards,
Alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Compare source code

2010-10-31 Thread Alan Harris-Reid


 Hi jf,

I use Beyond Compare (by Scooter Software) for comparing text files and 
find it an indespensible tool.  You can configure it so that it ignores 
tabs/whitespace, or treats spaces and tabs as different characters.  Not 
sure if it will work with compiled .pyc files, though (but then you 
wouldn't want to edit those, would you?)


Regards,
Alan


On 19:59, jf wrote:

Hi,

I've a project with tabs and spaces mixed (yes I know it's bad).

I edit each file to remove tabs, but it's so easy to make a mistake.
Do you know a tools to compare the initial file with the cleaned one 
to know if the algorithms are the same ?

By comparing pyc files for example.

Thanks.




-- 
http://mail.python.org/mailman/listinfo/python-list