Description
I'm using mypy 0.740 and I'm finding the way it handles branches to be fairly annoying. If you assign a variable along every branch, mypy infers its type but simply looking at the first assignment. This leads to a lot of code that's obviously correct, but that mypy thinks is wrong (in my codebase):
def foo(x: Union[str, int]):
pass
def bar(b: bool):
if b:
x = "hello"
else:
x = 7
foo(x)
I have code very similar to above in my codebase; mypy will infer the type of the local variable x
as str, and then complain when I assign an int. I'd suggest instead that if a variable is assigned in every branch, mypy take the union of the types. This comes up a lot with optional as well, where you assign x
to some value in one branch, but None
in the other. To resolve this, I explicitly set the type of x
by writing x: Union[str, int]
above the branch. The alternative would be doing it in the first branch, but this is asymmetric between the branches. On the other hand the way I've done it adds a whole line with no purpose except type checking, which is annoying as well (pick your poison).
Anyway quite possibly I'm totally wrong and there are counter-examples showing this is a terrible idea, or maybe it's super hard to implement, or maybe this is already implemented in the latest version. Just throwing it out there; generally mypy works very well with local variables. I generally only annotate functions and dataclasses and everything works fine, but this is proving to be the major exception for me.