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?
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')
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With