Keyword-only parameters for more explicit API

When you define a function, you're defining an API. To help write more explicit APIs, Python 3 allows you to write the function's parameters so that some of them are keyword-only. A keyword-only parameter gets its value only from a keyword argument in the call syntax.

def frobnicate(lorem, ipsum, *, dolor, sit=None, amet="spam"):
    """ Frobnicate the `lorem` to `ipsum`, with much `dolor`. """
    # …

We are accustomed to the TypeError raised when the arguments passed to a function don't match its signature. For example, when not all of the required arguments are provided:

>>> frobnicate(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: frobnicate() missing 1 required keyword-only argument: 'dolor'

By declaring the dolor parameter keyword-only, it is a TypeError to attempt to pass a third positional argument:

>>> frobnicate(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: frobnicate() takes 2 positional arguments but 3 were given

The parameter dolor (also sit and amet) cannot be passed as positional arguments, only as a keyword argument:

>>> frobnicate(1, 2, dolor=3)

Of course, keyword arguments may also be used for either of lorem and ipsum, if the caller chooses:

>>> frobnicate(1, dolor=3, ipsum=2)

Keyword-only parameters supported in Django 2.0

Django 2.0 brings keyword-only parameters to function definitions in more places:


Do you have questions about Django, or want to hire me for some work in a Django-related project? Come chat to me either privately at my Matrix address @bignose:matrix.org, or in the public Django chat channel.