user907629
user907629

Reputation: 534

A function with non keyword arguments and keyword arguments

If I declare a function with non keyword arguments such as a tuple and keyword arguments such as a dictionary, are they declared?

For example:

def someFunc(a, *nkw, **kwa):
    nkwList = []
    kwList  = []
    for i in nkw:
        nkwList.append(i)
    for j in kwa:
        kwList.append(j)
    print a, nkwList, kwList

Input:

someFunc(1)

Output:

1 [] []

As you can see, even though I did not pass a tuple and a dictionary, I didnot get Index out of range error when I loop through nkw and kwa. From my understanding, I think *nkw and **kwa are created in the function declaration itself.

Can anyone help me understand this concept?

Upvotes: 0

Views: 526

Answers (2)

mata
mata

Reputation: 69042

nkw and kwa are of course passed as emty list/dict. Doing something else would completely defy their purpose, as you could never access them safely, you't always have to check if they exist.

Your probably confusing this witht the default parameters. For example:

def someFunc(x=[]):
    pass

Here the list used as default for x is instantiated on declaration of the function, an therfore is the same on all invocations of the function.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

The tuple and dictionary are always created, even if they are empty (i.e. nothing was passed in them).

Upvotes: 1

Related Questions