Re: accessing class attributes

2008-05-28 Thread giltay
On May 28, 12:09 pm, eliben <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a game class, and the game has a state. Seeing that Python has
> no enumeration type, at first I used strings to represent states:
> "paused", "running", etc. But such a representation has many
> negatives, so I decided to look at the Enum implementation given 
> here:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
[...]
> Is there any better way, to allow for faster access to this type, or
> do I always have to go all the way ? What do other Python programmers
> usually use for such "enumeration-obvious" types like state ?

I tend to use string constants defined at the module level, e.g.:

##- in jobclass.py:
# Status indicators
IDLE = 'IDLE'
RUNNING = 'RUNNING'
FINISHED = 'FINISHED'

class Job(Thread):
def __init__(self):
Thread.__init__(self)
self.status = IDLE

def run(self):
self.status = RUNNING
self.do_work()
self.status = FINISHED
[...]
##- in another module
job = jobclass.Job()
job.start()
while job.status == jobclass.RUNNING:
print 'Job is running.'
time.sleep(SLEEP_SECONDS)
##-

I've also used dummy objects, eg:

##-
class RunStatus:
pass


IDLE = RunStatus()
RUNNING = RunStatus()
FINISHED = RunStatus()
##-

I've had lots of success with these two methods.  If you think an
enumeration is the most appropriate way, then:

##-
RunStatuses = Enum('idle', 'running', 'finished')
IDLE = RunStatuses.idle
RUNNING = RunStatuses.running
FINISHED = RunStatuses.finished
##-

I figure if you're only going to have a few dozen enumeration values,
then don't worry about cluttering up the module namespace with
variable names for constants.

Geoff G-T
--
http://mail.python.org/mailman/listinfo/python-list


Re: Producer-consumer threading problem

2008-06-11 Thread giltay
> Sounds like a sentinel would work for this.  The producer puts a
> specific object (say, None) in the queue and the consumer checks for
> this object and stops consuming when it sees it.  But that seems so
> obvious I suspect there's something else up.

 There's a decent implementation of this in the Python Cookbook,
Second Edition (9.4: Working with a Thread Pool), available from
Safari as a preview:
http://my.safaribooksonline.com/0596007973/pythoncook2-CHP-9-SECT-4

 Basically, there's a request_work function that adds (command,
data) pairs to the input Queue.  The command 'stop' is used to
terminate each worker thread (there's the sentinel).
stop_and_free_thread_pool() just puts N ('stop', None) pairs and
join()s each thread.

 The threadpool put()s the consumed items in an output Queue; they
can be retrieved concurrently using get().  You don't call join()
until you want to stop producing; you can get() at any time.

Geoff Gilmour-Taylor

(I ended up using this recipe in my own code, but with a completely
different stopping mechanism---I'm using the worker threads to control
subprocesses; I want to terminate the subprocesses but keep the worker
threads running---and a callback rather than an output queue.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterating "by twos"

2008-07-29 Thread giltay
On Jul 29, 1:36 pm, kj <[EMAIL PROTECTED]> wrote:
> Is there a special pythonic idiom for iterating over a list (or
> tuple) two elements at a time?

 I use this one a lot:

for x, y in zip(a, a[1:]):
frob(x, y)

Geoff G-T

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


Re: iterating "by twos"

2008-07-29 Thread giltay
On Jul 29, 2:36 pm, [EMAIL PROTECTED] wrote:
> On Jul 29, 1:36 pm, kj <[EMAIL PROTECTED]> wrote:
>
> > Is there a special pythonic idiom for iterating over a list (or
> > tuple) two elements at a time?
>
>      I use this one a lot:
>
> for x, y in zip(a, a[1:]):
>     frob(x, y)
>
> Geoff G-T

 Whoops, I misread the original post.  That would be:

for x, y in zip(a[::2], a[1::2]):
frob(x, y)

... which I don't use a lot.

>>> a = range(9)
>>> for x, y in zip(a, a[1:]):
... print x, y
...
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
>>> for x, y in zip(a[::2], a[1::2]):
... print x, y
...
0 1
2 3
4 5
6 7

Geoff G-T

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


Re: Boolean tests [was Re: Attack a sacred Python Cow]

2008-07-29 Thread giltay
On Jul 29, 1:30 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Jul 29, 5:15 am, Heiko Wundram <[EMAIL PROTECTED]> wrote:
>
> > I can't dig up a simple example from code I wrote quickly, but because of 
> > the
> > fact that explicit comparisons always hamper polymorphism
>
> I'm not going to take your word for it.  Do you have code that
> demonstrates how "if x" improves polymorphism relative to simple
> explicit tests?
>
> Carl Banks

I think "if x" works in some cases, but not in others.  Here's an
example I just made up and a counterexample from my own code.

Example:

Here's a function, print_members.  It's just something that takes some
iterable and prints its members in XML.  It's special-cased so that an
empty iterable gets an empty tag.  (This is a bit of a trivial
example, I admit; the point is that the empty iterable is a special
case.)

def print_members(iterable):
if not iterable:
print ''
return
print ''
for item in iterable:
print '%s' % item
print ''

>>> print_members(['a', 'b', 'c'])


a
b
c


>>> print_members([])



I could have used "if len(iterable) == 0:" for these cases, but only
because the length of a list means something.  Say I were to implement
a matrix class.  The length of a matrix isn't well-defined, so I won't
implement __len__.  I will, however, implement __nonzero__, since if
it has no members, it's empty.

class SimpleMatrix(object):

def __init__(self, *rows):
self.rows = rows

def __nonzero__(self):
for row in self.rows:
if row:
return True
return False

def __iter__(self):
return iter(sum(self.rows, []))

>>> a = SimpleMatrix([1, 2, 3], [4, 5, 6])
>>> print_members(a)


1
2
3
4
5
6


>>> b = SimpleMatrix([],[],[])
>>> len(b)

Traceback (most recent call last):
  File "", line 1, in 
TypeError: object of type 'SimpleMatrix' has no len()

>>> print_members(b)



So print_members can work on iterables that have no len(), and handle
the special case of an empty iterable, as long as __nonzero__ is
implemented.

Counterexample:

While "if x" works well in some circumstances, I don't like using it
for purely numeric types.  For instance, I have a mutable Signal class
for doing some basic DSP.  Among other things, I can apply a DC offset
to the signal (it just adds the offset to all the samples).  I have a
special case for an offset of 0 so I don't have to loop through all
the samples (I also have a two-pass remove_offset method that
subtracts the average; if it's already properly centred, I can skip a
step).

class Signal:
[...]
def dc_offset(self, amount):
if amount == 0:
return
self.samples = [sample + amount for sample in self.samples]

Here, "if amount == 0" is deliberate.  At no point should I be adding
an offset that's a list or a dict, even an empty one.
Signal.dc_offset should raise an exception if I try to do that,
because that indicates there's a bug somewhere.  If I do pass in [] or
{}, that test will fail, and it will try to add the list or dict to
the samples, at which point I get a TypeError.

Geoff G-T

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


Re: Boolean tests [was Re: Attack a sacred Python Cow]

2008-07-30 Thread giltay
On Jul 30, 5:09 am, Maric Michaud <[EMAIL PROTECTED]> wrote:
> Le Tuesday 29 July 2008 23:48:31 [EMAIL PROTECTED], vous avez écrit :
> > def print_members(iterable):
> >     if not iterable:
> >         print ''
> >         return
> >     print ''
> >     for item in iterable:
> >         print '%s' % item
> >     print ''
>
> But iterables can have no notion of emptiness too :
>
> >>>[25]: print_members((e for e in range(0)))
>
> 
> 

Ack!  Maybe I meant "container" rather than "iterable".  Or maybe I'd
be wrong on that count, too.  Other people have come up with better
examples, so I won't try to fix my hasty code (although I'll keep that
in mind if I have to write a custom XML writer).

> > class Signal:
> >     [...]
> >     def dc_offset(self, amount):
> >         if amount == 0:
> >             return
> >         self.samples = [sample + amount for sample in self.samples]
>
> This function is also wrong assuming that because amount compare to zero, it
> can be added to sample.

Not quite.  I'm assuming that if amount equals 0, then amount is some
scalar.  In fact, only if that comparison fails will I get my
exception: since [] != 0, it will then try to add sample + [], which
will raise TypeError.

> If you want to make type checking just check the type or convert your
> parameter to an int, but the test "== 0" is of no help here.

I'm not going for type checking here because I want Signal to support
int and float samples (and numpy.int16, &c.).

> The only valuable point I see for this idiom is to make more explicit I am
> testing a numerical value.

That's one of the reasons I wrote it that way.  Signal has other
methods that take lists (like mix and envelope), which I could get
confused with the ones that take scalars (offset and change volume).

 Cheers,
Geoff G-T
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterating "by twos"

2008-07-30 Thread giltay
On Jul 29, 4:11 pm, Erik Max Francis <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > for x, y in zip(a, a[1:]):
> >     frob(x, y)
>
> What you meant was this:
>
>  >>> [(x, y) for x, y in zip(a[::2], a[1::2])]
> [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>
> but this creates three sublists through slicing and zip.  The use of
> islice and izip is better, particularly if the list that's being
> iterated over is large.

 The lists I use it with are generally pretty small (a few
thousand items at most) so I decided to go with simple rather than
clever.  That said, I use it enough that it should become its own
function, at which point I'll probably grab something from this
thread.

 Cheers,
Geoff G-T
--
http://mail.python.org/mailman/listinfo/python-list


Re: Run program from within Python

2008-08-06 Thread giltay
On Aug 6, 3:42 pm, frankrentef <[EMAIL PROTECTED]> wrote:
> stdout, stdin = popen2.popen2('c:\test\OpenProgram.exe 1 1')

What Mike said about subprocess.

Also, in regular Python strings, \t means a tab character.  You need
to replace \ with \\ in the programme path ('c:\\test\\OpenProgram.exe
1 1') or use a raw string (r'c:\test\OpenProgram.exe 1 1').  (The r
informs the Python parser that backslashes are to be used veratim, not
as special code.  If you're using Windows, raw strings make for fewer
headaches when dealing with file paths.)

Geoff G-T

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


Re: improving a huge double-for cycle

2008-09-18 Thread giltay
On Sep 18, 11:18 am, [EMAIL PROTECTED] wrote:
> dup=set()
> SN=[]
> for item in IN:
>    c=item.coordinates[0], item.coordinates[1]
>    if c in dup:
>       SN.append(item.label)
>    else:
>       dup.add(c)

+1 for O(N)

If item.coordinates is just an (x, y) pair, you can skip building c
and save a little memory:

seen_coords = set()

for node in IN:
if node.coordinates in seen_coords:
SN.append(node.label)
else:
seen_coords.add(node.coordinates)

seen_coords gets populated with references to the existing
node.coordinates objects, instead of new tuples.

Geoff G-T

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


Re: Blanket font setting?

2008-09-18 Thread giltay
On Sep 18, 12:55 pm, RGK <[EMAIL PROTECTED]> wrote:
> Is there any sort of blanket font setting, perhaps like:
>
>    wx.SystemSettings_SetFont(font)   #this doesn't exist
>
> that could set everything with one fell swoop?
>
> Thanks for your attention...
>
> Ross.

I do this by setting the font in each frame (or dialog); the font
propogates to its descendants.

http://lists.wxwidgets.org/pipermail/wxpython-users/2008-September/080099.html

Geoff G-T
--
http://mail.python.org/mailman/listinfo/python-list


Re: improving a huge double-for cycle

2008-09-19 Thread giltay
On Sep 18, 7:42 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> I'm not being snarky about losing priority here, but I submitted
> essentially the same solution two hours earlier than pruebono.

My apologies (seriosuly).  In this case, I think it might just be
haste.  For what it's worth, I saw your post (on Google Groups), but I
skipped over it.  You wrote two solutions, one slow and one fast (the
latter being the same as pruebono's).  You put the slow one at the
top, I saw

for ...
for ...

and went straight to the next message without reading the better
solution.  I knew that there was only one for loop necessary, so I
didn't bother reading on.  Actually, I missed pruebono's post, too,
until after I figured it out myself (but before I posted).

That several people came up with the nigh exact same solution, modulo
variable names only, says something about the Zen of Python.

Geoff G-T

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


Re: OS.SYSTEM ERROR !!!

2008-09-30 Thread giltay
On Sep 30, 1:21 pm, "Blubaugh, David A." <[EMAIL PROTECTED]> wrote:
> I would usually execute this program (with the appropriate arguments) by
> going to following directory within MS-DOS (Windows XP):
>
> C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0
[snip]
> import os
>
> os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0")
[snip]
> ERROR opening inputs/io/control.dat
[snip]

I would add the following line right before your call to os.system:

os.chdir(r'C:\myprogramfolder\run')

If you have to change directories to run it properly in the Windows
shell, then you need to do it in Python, too.

 HTH,
Geoff G-T

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