Are *parameters calls lazy? [duplicate]
Asked Answered
F

3

10

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

Let's say you have a function like this:

def give_me_many(*elements):
   #do something...

And you call it like that:

generator_expr = (... for ... in ... )
give_me_many(*generator_expr)

Will the elements be called lazily or will the generator run through all the possibly millions of elements before the function can be executed?

Firetrap answered 16/8, 2012 at 11:59 Comment(2)
#5183258Niccolo
@thg435 I have to agree.Firetrap
D
12

no they are not:

>>> def noisy(n):
...   for i in range(n):
...     print i
...     yield i
... 
>>> def test(*args):
...   print "in test"
...   for arg in args:
...     print arg
... 
>>> test(*noisy(4))
0
1
2
3
in test
0
1
2
3
Dispersoid answered 16/8, 2012 at 12:3 Comment(0)
S
14

Arguments are always passed to a function as a tuple and/or a dictionary, therefore anything passed in with *args will be converted to a tuple or **kwargs will be converted to a dictionary. If kwargs is already a dictionary then a copy is made. tuples are immutable so args doesn't need to be copied unless it changes (by including other positional arguments or removing some arguments to named positional ones), but it will be converted from any other sequence type to a tuple.

Slyviasm answered 16/8, 2012 at 12:6 Comment(3)
Sounds logical, but I still don't get the connection to the question.Firetrap
@erikb85, the call to tuple(..) (or dict(..)) for the conversion force the evaluation of the whole generator.Tripartition
Timeit seems to confirm that calling f(*some_tuple) is slightly faster than calling f(*some_list). Huh.Pannikin
D
12

no they are not:

>>> def noisy(n):
...   for i in range(n):
...     print i
...     yield i
... 
>>> def test(*args):
...   print "in test"
...   for arg in args:
...     print arg
... 
>>> test(*noisy(4))
0
1
2
3
in test
0
1
2
3
Dispersoid answered 16/8, 2012 at 12:3 Comment(0)
C
0

The docs say that

These arguments will be wrapped up in a tuple

which means that the generator is evaluated early.

Ceremonial answered 16/8, 2012 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.