Tuple assignment and generators?

Tim Chase python.list at tim.thechases.com
Thu May 4 11:09:34 EDT 2006


Just as a pedantic exercise to try and understand Python a 
bit better, I decided to try to make a generator or class 
that would allow me to unpack an arbitrary number of 
calculatible values.  In this case, just zeros (though I 
just to prove whatever ends up working, having a counting 
generator would be nice).  The target syntax would be 
something like

 >>> a,b,c = zeros()
 >>> q,r,s,t,u,v = zeros()

where "zeros()" returns an appropriately sized tuple/list of 
zeros.

I've tried a bit of googling, but all my attempts have just 
ended up pointing to pages that blithly describe tuple 
assignment, not the details of what methods are called on an 
object in the process.

My first thought was to get it to use a generator:

	def zeros():
		while 1: yield 0

However, I get back a "ValueError: too many values to 
unpack" result.

As a second attempt, I tried a couple of attempts at classes 
(I started with the following example class, only derived 
from "object" rather than "list", but it didn't have any 
better luck):

 >>> class zeros(list):
...     def __getitem__(self,i):
...             return 0
...
 >>> z = zeros()
 >>> a,b,c = z
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
ValueError: need more than 0 values to unpack


It looks like I need to have a pre-defined length, but I'm 
having trouble figuring out what sorts of things need to be 
overridden.  It seems like I sorta need a

	def __len__(self):
		return INFINITY

so it doesn't choke on it.  However, how to dupe the 
interpreter into really believing that the object has the 
desired elements is escaping me.  Alternatively if there was 
a "doYouHaveThisManyElements" pseudo-function that was 
called, I could lie and always return true.

Any hints on what I'm missing?

Thanks,

-tkc











More information about the Python-list mailing list