Enforcement of function keyword arguments in Python
Before starting in my new role a couple of months ago, it had been a very long time since I had programmed in Python.
Incidentally, I kept working in roles over the past several years that involved either full-stack Javascript or mostly Javascript with a little bit of another language (most recently Go).
So it's been fun to stretch my muscles a bit in a different language, especially one as accessible as Python is.
One feature of the language that I'm enjoying right now is the enforcement of keyword arguments to functions using the kw_only
property made accessible in the @dataclass
decorator.
It makes code that looks like this:
from dataclasses import dataclass
@dataclass(kw_only=True)
class Person:
name: str
age: int
city: str
person1 = Person("Alice", 30, "New York")
raise an error, because the use of kw_only
expects to see something like the following:
from dataclasses import dataclass
@dataclass(kw_only=True)
class Person:
name: str
age: int
city: str = "Unknown"
person1 = Person(name="Alice", age=30, city="New York")
Although the error raised:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 10
7 city: str = "Unknown"
---> 10 person1 = Person("Alice", 30, "New York")
TypeError: Person.__init__() takes 1 positional argument but 4 were given
is "clear" in that it will indicate to you that there are too many positional arguments being provided, if you're not familiar with kw_only
it can be a bit puzzling because it looks like you're invoking the function properly.
If you come from a background of Javascript/Typescript like I do, or have previous experience with languages like Go or Rust that enforce this using something like struct
s where you're able to provide the arguments in whatever order you like as long as the properties follow the shape of the object/struct, then this will feel familiar and likely a welcome addition to your Python code.
This is especially useful if you're working with a large number of arguments, some of which may be optional.
Like what you've read?
Subscribe to receive the latest updates in your inbox.