The import is technically necessary because the decorator is implemented in Python[1] in the dataclasses.py
module. The basic behaviour and concept (analysing annotations, generating source code and then exec
on the result) are largely inherited from the attrs
project others have mentioned.
If the current implementation (or something based on it) was imported by default at startup and included in builtins it would be a significant regression in Python startup time. There have been previous discussions about having something more ‘baked-in’ both for startup and class generation performance, but no consensus on what that should look like.
Personally I would disagree on this being an improvement over autogenerated __repr__
and __eq__
.
It’s fairly easy to leave out a __repr__
when defining classes by hand so including one ‘by default’ means that it’s more likely I can see useful information in tracebacks where other people have used @dataclass
. __eq__
by default I find most useful when writing tests on functions that have dataclasses as output - the only downside being that by default the classes are not hashable (as with any class with __eq__
defined without __hash__
).
I don’t consider locally defined aliases to be a band-aid. I consider it to be customising the tool for your use case.
I actually somewhat wish dataclasses was more modular so it was easier to modify the workings. The collection of attributes and generation of methods all happens within _process_class
so it’s not really possible with dataclasses to separate analysis from generation.
I’d love to - for instance - have a metaclass that generated slots before a class was created[2] and put the necessary analysis details somewhere else and allowed dataclasses to write the methods based on the pre-gathered details.