Some Python 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 with default values must come after those without.

When you call a function, you may — if you like — supply parameter names (“named args”, as in my_func(foo=1)), regardless of whether or not the param had a default value when the function was defined. 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(..., *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.