How to Create a Keyword-Only Function in Python

Require variable names for each parameter in your function calls

How to Create a Keyword-Only Function in Python
Photo by Mick Haupt on Unsplash

Starting in Python 3.8, it is possible to explicitly define function parameters as being keyword only.

What is a keyword parameter? Traditionally when you define and call a function, the parameters are listed in order and must be called in the same arrangement. This means that the first passed value is assigned to the first defined parameter and so on.

Previously in Python, functions with default values in the parameters could also be called via keyword.def areaRectangle(length=1, width=1):
  print("Length:", length)
  print("Width:", width)
  print("Area:", length * width)areaRectangle(3,5)
"""
Length: 3
Width: 5
Area: 15
"""areaRectangle(width=3, length=5)
"""
Length: 5
Width: 3
Area: 15
"""

While flexible, there is a desire for being explicit in the definition of a function.


Defining Keyword Only Functions

If you want to define a function where all parameters are required to be referenced by their variable name, begin your parameter list with an asterisk as the first parameter.def areaRectangularPrism(*,length, width, height):
  return length * width * heightareaRectangularPrism(3,4,5)
# TypeError: areaRectangularPrism() takes 0 positional arguments but 3 were givenareaRectangularPrism(width=3, height=4, length=5)
# 60

Notice that passing positional arguments results in a TypeError. Also, make sure you separate the asterisk and the first parameter with a comma. Consider them two separate parameters.

So when would you want to define a keyword-only function?

I’ve found success using keyword-only functions when the parameter list is lengthy and all parameters have default values. In these circumstances, the function could be passed empty or with any arrangement of arguments. Times like these, requiring keywords makes the call more explicit and easier to read—in my opinion.

Subscribe to Dreams of Fortunes and Cookies

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe