python-attrs / attrs

Python Classes Without Boilerplate
https://www.attrs.org/
MIT License
5.3k stars 373 forks source link

Inheritance breaks mypy type checking with optional attributes if Generics are involved #1028

Open rggjan opened 2 years ago

rggjan commented 2 years ago

Inheritance breaks mypy type checking with optional attributes if Generics are involved:

from typing import Generic, Optional, TypeVar

import attr

T = TypeVar("T")

@attr.mutable()
class Parent(Generic[T]): # Removing `Generic` here and `[float]` below doesn't show `mypy` issues anymore
    run_type: Optional[int] = None

@attr.mutable()
class Child(Parent[float]):
    pass

Parent(
    run_type =None,
)

Child(
    run_type =None, # error: Argument "run_type" to "Child" has incompatible type "None"; expected "int"  [arg-type]
)

There is an error displayed which is wrong. Doing the same without any Generic involved works as expected.

Not quite sure if this is a mypy issue or an attrs typing issue.

billtrik commented 2 years ago

Same issue

hynek commented 2 years ago

Is this a dupe of https://github.com/python-attrs/attrs/issues/452?

rggjan commented 2 years ago

I don't think so. In #452, the type itself is generic, which is causing issues. In my example, the types of the attributes are fixed and independent of "T", but inheriting from Generic still breaks the types.

hynek commented 2 years ago

@euresti? @Tinche? 🥺

Tinche commented 2 years ago

Maybe @sobolevn might be able to give it a shot?

euresti commented 2 years ago

Weird. I don't get an error with mypy 0.950

$ mypy --version
mypy 0.950 (compiled: yes)

I do have a quick question since I can't repro. If this was re-written without attrs does it still have the same problem?

rggjan commented 2 years ago

I think we only started seeing this in newer mypy version. Could also be a mypy issue?

Try with mypy 0.981

sobolevn commented 2 years ago

Yes, looks like a mypy issue. Please, open a new report there :)