Tuple assignment and generators?

Diez B. Roggisch deets at nospam.web.de
Thu May 4 12:00:15 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

<snip/>

By using this:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284742


I came up with a small decorator doing that:

import inspect, dis

def expecting():
    """Return how many values the caller is expecting"""
    f = inspect.currentframe()
    f = f.f_back.f_back
    c = f.f_code
    i = f.f_lasti
    bytecode = c.co_code
    instruction = ord(bytecode[i+3])
    if instruction == dis.opmap['UNPACK_SEQUENCE']:
        howmany = ord(bytecode[i+4])
        return howmany
    elif instruction == dis.opmap['POP_TOP']:
        return 0
    return 1

def variably_unpack(f):
    def d(*args, **kwargs):
        r = f(*args, **kwargs)
        exp = expecting()
        if exp < 2:
            return exp
        return (r.next() for i in xrange(exp))
    return d

@variably_unpack
def test():
    def gen():
        i = 0
        while True:
            yield i
            i += 1
    return gen()



a, b, c = test()

print a,b,c

a, b, c, d = test()

print a,b,c, d



Diez





More information about the Python-list mailing list