In the following code, the valid
function and the invalid
function do exactly the same thing. Why is MyPy happy with valid
, but throws an error on invalid
?
Isn't the TypeGuard
suppose to handle that?
If I add a function to B
and C
only, and call that function from within a block guarded by ifBorC
, that works fine.
Does MyPy not look at type guards when dealing with completeness of union types?
from typing import TypeGuard
class A: ...
class B: ...
class C: ...
ABC = A | B | C
BorC = B | C
def isBorC (x: ABC) -> TypeGuard[BorC]:
return isinstance(x, B) or isinstance(x, C)
def valid (x: ABC) -> str:
if isinstance(x, A):
return 'a'
if isinstance(x, B) or isinstance(x, C):
return 'b or c'
def invalid (x: ABC) -> str:
if isinstance(x, A):
return 'a'
if isBorC(x):
return 'b or c'
# Yields error: Missing return statement [return]