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

3

10

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?

Mcadoo answered 3/3, 2011 at 15:26 Comment(0)
D
14

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')
Deodar answered 3/3, 2011 at 15:29 Comment(1)
It would be good to add to the end of the example that calling f(*gen) a second time returns (), to show that invoking f exhausts the generator for subsequent lines.Expression
C
2

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.

Concoction answered 3/3, 2011 at 15:28 Comment(1)
Whenever you have f(*arg), arg itself will be always be a tuple at the functionPitchman
S
-2

Your don't really need

gen = (f for f in foo)

Calling

f(*foo)

will output

('foo', 'bar', 'baz')
Shivaree answered 9/12, 2012 at 14:53 Comment(2)
This is just the simplest possible generator, for demonstration purposes--an "identity" generator, if you will.Mcadoo
This doesn't answer the question at all - the OP definitely intended for an analytic answer that generalised for any generator.Dianemarie

© 2022 - 2024 — McMap. All rights reserved.