Use keyword-only arguments in Python dataclasses
28 points by ubernostrum
28 points by ubernostrum
Another great dataclass parameter is frozen=True
, which marks your dataclasses as immutable. Hopefully the benefits of immutability speak for themselves, but it also makes your dataclass hashable for free, allowing you to use them in sets/as keys dict keys.
I used to be annoyed by keyword-only in Pydantic and debated changing the default for a long time, but I’ve come around on wanting keyword-only on any class construction because it’s explicit and easy to change which is more valuable to me now than making the code shorter.
This is such a good tip, thanks for sharing. Some of my projects could have used this. I admit I still don’t know much of the @annotation
system in Python.
Is there something else like this, especially for creating enum classes?
I admit I still don’t know much of the @annotation system in Python.
These are called decorators in Python. They are just callables that take callables as arguments to wrap it, a way to do metaprogramming.
I admit I still don’t know much of the
@annotation
system in Python.
This:
@some_decorator
def my_function():
print("Hello")
is exactly equivalent to this:
def my_function():
print("Hello")
my_function = some_decorator(my_function)
The @
form is just syntactic sugar. You can do it to a function, a method, or a class. There are a lot of use cases, ranging from simple things like adding pre/post-call actions (like logging) to complex transformations, to adding objects to a registry, to… well, anything you can think of that’s legal to do in a Python function.
Something like what? https://docs.python.org/3/library/enum.html has been there a while if you need C-ish enums (and / or flags).
If you want something closer to sum types, https://docs.python.org/3/library/typing.html#typing.Union and simple newtypes (e.g. trivial dataclasses with a single member) is probably what you’re looking for.
Yeah that was it, thanks! :)
Don’t get confused though, typing.NewType is type checking -time only, hence their recommendation to use dataclasses.