Pytype gives wrong type for optional attributes in dataclasses
Using pytype-2020.8.17:
from typing import Union
import dataclasses
@dataclasses.dataclass
class X:
a: Union[None, int]
def f(x: X):
reveal_type(x.a)
gives a type of Union[Any, int] for x.a instead of the expected Union[None, int].
the root cause is we have some code that tries to filter out false positives on assigning None to a variable, and it's unfortunately generating a false false positive here.
(that is, when analysing the body of f() we wrongly infer that x.a can never be None, and hence convert the None to Any)
Thanks for looking into it! May I ask if it's on the roadmap to resolve this at some point?
it's definitely something we want to fix - we've added it to our general bugfix roadmap, but without any priority dates just yet.
Is the proper solution to have an upper and lower bound and what elements in the sum are allowed and to have contravariance annotations (that flip upper and lower bound) ? This is fairly standard technique in some languages and perhaps could be copied.
i don't think the problem is with the way we bound types - it's a hard-to-track-down bug in the way we track variable origins and reachability in the control flow graph. (if you're curious, the problem manifests in this function but the bug itself is whatever added the origins wrongly.)