Question

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?

Était-ce utile?

La solution

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

Autres conseils

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.

The docs say that

These arguments will be wrapped up in a tuple

which means that the generator is evaluated early.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top