attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Typing not working properly when positional argument is defined in subclass with redefined kwargs

Open Rizhiy opened this issue 3 years ago • 4 comments

Describe the bug Using pyright for type checking produces the following errors:

from attrs import define


@define
class A:
    foo: int
    bar: str = "baz"


@define
class B(A):
    zoo: float
    bar: str = "zaz"


b = B(1, 2.7)
print(b)
>>> B(foo=1, zoo=2.7, bar='zaz')

image image

Not sure whether the problem is with attrs type definitions or with pyright, so will create issues in both places.

Perhaps types are not defined properly somewhere?

Rizhiy avatar Sep 07 '22 01:09 Rizhiy

Unfortunately this is not something that is within our power to fix. The interpretation of attributes and deducting the created __init__ is the task of the type checker. In Mypy your example passes just fine, so Pyright is the correct place to report this.

hynek avatar Sep 10 '22 09:09 hynek

Pyright simply assumes that attrs works the same way as dataclasses. dataclass wants to put bar before zoo and errors. PEP 681 states:

  • Field ordering and inheritance is assumed to follow the rules specified in :pep:557 <557#inheritance>. This includes the effects of overrides (redefining a field in a child class that has already been defined in a parent class).

And under 'Rejected Ideas':

The attrs library differs from stdlib dataclasses in how it handles inherited fields that are redeclared in subclasses. The dataclass specification preserves the original order, but attrs defines a new order based on subclasses.

For simplicity, we chose to only support the dataclass behavior. Users of attrs who rely on the attrs-specific ordering will not see the expected order of parameters in the synthesized __init__ method.

Unfortunately, you can't get very creative with attrs if you're using Pyright.

layday avatar Sep 10 '22 09:09 layday

I would like to stress here that dataclasses violate the MRO and nobody cares.

hynek avatar Sep 10 '22 09:09 hynek

Well, that's a separate issue, right? This is just about parameter order in a single inheritance scenario.

layday avatar Sep 10 '22 10:09 layday