Enforcement of function keyword arguments in Python

Patricia Arquette
Release: 2024-10-22 12:51:02
Original
813 people have browsed it

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")
Copy after login

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")
Copy after login

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
Copy after login

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 structs 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.

The above is the detailed content of Enforcement of function keyword arguments in Python. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template