Tuple assignment and generators?

Tim Chase python.list at tim.thechases.com
Thu May 4 21:34:30 CEST 2006

> I don't think he was explicitly wanting to initialize
> things to zero, but rather unpack an arbitrary sequence
> into a tuple (could perhaps be the fibonnacci sequence
> for example).

Ant is correct here...Fibonnaci, digits of pi, the constant
42, an incrementing counter, a series of squares, whatever. 
  That was my original intent in the matter.  Zeros just 
happened to be a nice sort of place to start my exercise.

> How about:
>>>>def zeros(count):
> ...     for i in range(count):
> ...         yield 0

One of the things I was trying to avoid was having to know 
(and maintain) the count of items initialized.  In the 
theoretical world of my example, one could do something like

def counter():
	counter = 0
	while 1:
		yield counter
		counter += 1

and then initialize several variables, such as

 >>> a,b,c,d,e,f,g = counter()
 >>> a,b,c,d,e,f,g

It's similar to C's auto-numbering of enum values...If I 
want to add another entry to a C enum, I just put it there, 
and let the language take care of matters.  With most of the 
provided solutions, I also have to increment the count each 
time I add an item to the list.

Diez provided an elegant solution with a decorator 
(employing an incredibly ugly sort of hack involving 
sniffing the opcode stack behind the scenes) that does what 
I was looking for.

I was hoping that there was just some __foo__ property I was 
missing that would have been called in the process of tuple 
unpacking that would allow for a more elegant solution such 
as a generator (or generator method on some object) rather 
than stooping to disassembling opcodes. :)

Ah well.


More information about the Python-list mailing list