python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.34k stars 2.81k forks source link

False negative when lvalue has union type #17859

Open JukkaL opened 2 weeks ago

JukkaL commented 2 weeks ago

Mypy generates no error, even though the code is unsafe:

class C[T]:
    a: T

def f(x: C[int] | C[str]) -> None:
    x.a = 1  # No error

c = C[str]()
f(c)
print(c.a, type(c.a))  # 1, int

I'd expect x.a = 1 to generate an error, since the assignment is unsafe.

I suspect that the lvalue type is inferred as int | str, and mypy thinks it's fine. instead, assignment should be valid for each union item separately.

chelseadz commented 4 days ago

Hi! I would like to work in this issue, just a question, where should I add a test for this case?