PyGrunn: args, kwargs, and all other ways to design your function parameters - Mike Huls

Tags: pygrunn, python

(One of my summaries of the 2024 Dutch PyGrunn python&friends conference in Groningen, NL).

Python is easy to use, but it is also easy to use in a wrong way. The goal of this talk is to get a better design for your functions.

Some definition:

  • Arguments versus parameters: parameters are the placeholders/names, arguments are the actual values. So some_function(parameter="argument").

  • Type hinting: hurray! Do it! It makes your parameters clearer.

  • Arguments versus keyword arguments. Keyword arguments are less error-prone and are more readable but also are more work. some_function("a1", "a2", "a3") versus some_function(p1="a1", p2="a2", p3="a3") He did some testing and keyword arguments are a tiny, tiny bit slower, but nothing to worry about.

  • Defaults. Handy and fine, but don’t use “mutable types” like a list or a dict, that’s unsafe.

Behind the scenes, what happens when you call a function:

  • Stack frame creation (a packages that contains all the info for the function to be able to run).

  • Arg evaluation and binding.

  • Function executes.

  • Transfer control back to the part that called the function.

  • Garbage control, the regular python cleanup.

Some handy functionality apart from regular args and kwargs:

  • def some_function(a, b, *args):, args are the left-over arguments if not all of them matched. args is a tuple.

  • def some_function(a="a", b="b", **kargs):, same for keyword arguments. This is a dict.

  • def some_function(*, a="a", b="b"):, the asteriks at the start “eats up” all the non-keyword arguments, ensuring it is impossible to pass positional arguments to the keywords. This makes your code safer.

  • def some_function(a, b, /):, the slash says that everything before it has to be a positional parameter, it is forbidden from being used at a keyword argument. You rarely need this.

A variant is def some_function(positional1, *, /, mandatory_kwarg=None), with one mandatory positional argument and one mandatory keyword argument.

So… with a bit of care you can design nice functions. logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):