Python Notes and Examples
← prev | next →     Top-level ToC     /functions.html     (printable version)

When you define a function, you of course have to list all the parameters. Any params with default values must come after those without.

When you call a function, you may — if you like — supply named arguments, regardless of whether or not the param had a default value when the function was defined.

# One positional parameter.
def foo(n):

foo(5)   # Yup
foo(n=5) # Calling with named argument is fine too.
foo(x=5) # Error

# Param with default value.
def bar(n=3):

bar(5)   # Yup
bar(n=5) # Fine too
bar()    # Fine too
bar(x=5) # Error

If you supply all param names, you can pass in the args in any order you like.

1 Varargs

If a function is defined like def foo(a, b, *foo, **bar), then any extra positional args passed to it get soaked up into a tuple foo in the body of the function, and any extra named args go into the bar dict.

2 Unpacking args

When calling a function, you can unpack args by putting a * or ** in front of them:

xs = ['a', 'b', 'c']
# Function foo takes three args. So:
foo(*xs)  # Like `foo('a', 'b', 'c')`.

d = {'a': 1, 'b': 2, 'c': 3}
# Function bar was defined with three params: a, b, & c.

3 Varargs, Unpacking, and Dicts

All together:

def foo(**m):
    print('-->', m)

m2 = {'a': 1, 'b': 2, 'c': 3}

# --> {'a': 1, 'c': 3, 'b': 2}

So, it’s as if m2 gets unpacked, but then repacked into the m parameter.