Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do python's variable length arguments (*args) expand a generator at function call time?

Consider the following Python code:

def f(*args):
    for a in args:
        pass

foo = ['foo', 'bar', 'baz']

# Python generator expressions FTW
gen = (f for f in foo)

f(*gen)

Does *args automatically expand the generator at call-time? Put another way, am I iterating over gen twice within f(*gen), once to expand *args and once to iterate over args? Or is the generator preserved in pristine condition, while iteration only happens once during the for loop?

like image 503
David Eyk Avatar asked Mar 03 '11 15:03

David Eyk


2 Answers

The generator is expanded at the time of the function call, as you can easily check:

def f(*args):
    print(args)
foo = ['foo', 'bar', 'baz']
gen = (f for f in foo)
f(*gen)

will print

('foo', 'bar', 'baz')
like image 166
Sven Marnach Avatar answered Sep 22 '22 05:09

Sven Marnach


Why not look and see what gen is in f()? Add print args as the first line. If it's still a generator object, it'll tell you. I would expect the argument unpacking to turn it into a tuple.

like image 33
kindall Avatar answered Sep 25 '22 05:09

kindall