Warn about un-annotated attributes in dataclass definition #12877
Labels
great writeup
A wonderful example of a quality contribution
rule
Implementing or modifying a lint rule
This is a feature request. The proposal is for a warning which would be triggered if a dataclass definition contains un-annotated attribute declarations. Attributes
d
ande
in the following example would trigger the warning:Pitch
By default, all attributes defined in a dataclass definition are class attrtibutes. Those annotated with a type also become instance attributes, unless their annotation is
typing.ClassVar
. This leads to the potentially surprising behaviour that un-annotated attributes are automatically only class attributes. DoingBar(d=1)
orBar(e="bar")
using the above definition leads to an "unexpected keyword argument" error, which itself does not immediately indicate (to novice Python programmers) thatd
ande
are class attributes. This is especially dangerous when considering to offer a dataclass as public API for users to subclass (comments in the example).I propose that ruff could at least prompt developers to clarify that they intend for an attribute to be a class attribute by using
typing.ClassVar
. Type annotations are frequently described as "optional", however in this case, by leaving them out, the semantics of the attribute declaration changes. The decision on whether to prompt the addition of "optional" type annotations is also being discussed in #5243, which is about the related RUF012 rule. However, that rule only covers the case of mutable class attributes (ife
were a list, in the above example), and its scope extends beyond dataclasses. Because the use of dataclasses arguably implies the use of annotations, I think it is reasonable to warn when they are missing.I'm not sure if this would be best proposed as a Pylint warning, or as a Ruff-only rule, but considering the classification of RUF012 I chose to propose it here.
I also opened a possibly premature issue over at mypy and started a discussion on the forum.
The text was updated successfully, but these errors were encountered: