Tuple assignment and generators?

Larry Bates larry.bates at websafe.com
Thu May 4 12:17:08 EDT 2006


Tim Chase wrote:
> 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
> 
> 
While I have never needed anything like this in my 5 years of Python
programming, here is a way:

a,b,c = 3*[0]
q,r,s,t,u,v = 6*[0]

of if you like:

def zeros(num):
    return num*[0]

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

I think the reason I don't every use anything like this is that
you don't need to initialize variables in Python to zero and I would
probably use a list instead of individual variables like q,r,s,t,u,v.

-Larry Bates




More information about the Python-list mailing list