mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Fix `@dataclass` to catch default / non-default fields order

Open sobolevn opened this issue 3 years ago • 7 comments

Closes https://github.com/python/mypy/issues/12137

sobolevn avatar Feb 10 '22 10:02 sobolevn

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

github-actions[bot] avatar Feb 10 '22 10:02 github-actions[bot]

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

github-actions[bot] avatar Feb 10 '22 11:02 github-actions[bot]

So, here's what happens with overriding kw-only with a regular field.

from dataclasses import dataclass, field

@dataclass
class Some:
    x: int = field(kw_only=True)

@dataclass
class Other(Some):
    x: int

print(Other(1))  # Other(x=1)

Two fields (there was a difference in the original bug report):

from dataclasses import dataclass, field

@dataclass
class Some:
    x: int = field(kw_only=True)

@dataclass
class Other(Some):
    x: int
    y: int

print(Other(1, 2))

Mypy is also happy with this. So, I've just added a test case to cement this behavior (which I believe is the correct one).

Funny thing

But, while testing this, I found a different problem:

from dataclasses import dataclass, field, KW_ONLY

@dataclass
class Base:
    x: int
    y: int = field(kw_only=True)
    _: KW_ONLY
    z: int = 0

@dataclass
class Other(Base):  # E: Attributes without a default cannot follow attributes with one
    x: int
    y: int
    z: int

I will open a new issue for it and address in a separate PR (if this is a problem at all, some more analysis is needed).

sobolevn avatar Feb 13 '22 12:02 sobolevn

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

github-actions[bot] avatar Feb 13 '22 12:02 github-actions[bot]

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

github-actions[bot] avatar Feb 13 '22 12:02 github-actions[bot]

This is a new regression: https://github.com/python/mypy/issues/12173 It is not happening on master

sobolevn avatar Feb 13 '22 12:02 sobolevn

This still has a couple of regressions 😢 I will fix them later.

sobolevn avatar Feb 15 '22 05:02 sobolevn