Python Notes and Examples

Functions

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 your arguments as named arguments, regardless of whether or not the param had a default value when the function was defined. (These are sometimes called “keyword params/args”, reminiscent of “key/value pairs in a dict”).

If your args supply all param names (that is, if you call the function using named args), you can pass in the named args in any order you like.

Note that if you supply mutable default values in your function parameters, they are only evaluated once — when the function is defined — so they will persist between calls:

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 (of course, not a or b though, for this example) go into the bar dict.

Keyword-only params

You can specify some params be supplied only via named (“keyword”) args:

All args after the bare * must to be called using named args. In addition, of course, if you have a *p param, then any args passed after that must be keyword-only as well (otherwise they’d be positional and be soaked up by *p.

Unpacking args

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

If you accidentally did bar(*d), then only the keys of d would be unpacked and passed to bar.

Note, with:

the dict keys in must match exactly with the params of foo, but you can get them from more than one dict.

Varargs, Unpacking, and Dicts

All together:

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

Type Annotations

Python 3 introduced “function annotations”, where you could annotate functions with arbitrary strings:

Python 3.6 PEP 526 introduced syntax specifically for variable type annotations.

See also MyPy for adding type annotations, and static type-checking.

Nested Functions

You can define functions inside other functions: