Ormazd Ormazd - 1 year ago 58
Python Question

What is execution model for *args in function call?

I need to pass huge

to function through

def f(*args): # defined in foreign module

arguments = tuple(range(10000))

And I wonder what happens at function call.

Does it handle
similar to any positional variable: save it and access on-demand during body execution? Or does it iterate through
even before body execution, extending positional arguments? Or is it something else?

Answer Source

A simple test using a generator:

def gen():
    print('Yielding 1')
    yield 1
    print('Yielding 2')
    yield 2
    print('Yielding 3')
    yield 3

arguments = gen()
def f(*args):

# Yielding 1
# Yielding 2
# Yielding 3

As you can see from the output, passing *arguments will actually unpack the whole iterable, since technically, you are telling Python to pass the iterable as individual arguments using the *arguments syntax. It does not matter that the function definition also uses *args which makes Python pack the arguments back into a tuple again.

So yeah, you are unpacking the list only to pack it again here. You can avoid this by just passing the list directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download