Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are *parameters calls lazy? [duplicate]

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?

like image 441
erikbstack Avatar asked Aug 16 '12 11:08

erikbstack


2 Answers

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.

like image 113
Duncan Avatar answered Oct 20 '22 00:10

Duncan


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
like image 31
andrew cooke Avatar answered Oct 20 '22 00:10

andrew cooke