Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn about un-annotated attributes in dataclass definition #17666

Open
adigitoleo opened this issue Aug 13, 2024 · 1 comment
Open

Warn about un-annotated attributes in dataclass definition #17666

adigitoleo opened this issue Aug 13, 2024 · 1 comment
Labels

Comments

@adigitoleo
Copy link

Feature

MyPy could warn if a dataclass definition contains un-annotated attribute declarations. Attributes d and e in the following example would trigger the warning:

from dataclasses import dataclass

@dataclass
class Foo:
    a: float = 4.2
    b: int = 42
    c: tuple = (4.2, 42)
    d = 999
    e = "foo"

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. Doing Foo(d=1) or Foo(e="bar") using the above definition leads to an "unexpected keyword argument" error, which itself does not immediately indicate (to novice Python programmers) that d and e are class attributes.

I propose that if someone is using mypy, they should be at least prompted 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. It is also arguable whether this behaviour is presented clearly enough in the documentation (we have to infer that "fields" are instance attributes, and they require a type annotation, therefore un-annotated variables are left as regular class attributes).

@adigitoleo
Copy link
Author

Actually, this request overlaps quite a bit with the existing RUF012 rule from ruff, which is already subject to debate: astral-sh/ruff#5243. In that case, I suppose there is not much hope for this one. For posterity, there is also this python.org post where I initially voiced the concern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant