In Python, we can assign a type to an variable in this way and pass mypy's typecheck:
from typing import Type, Union
class Foo:
pass
MyType: Type[Foo] = Foo
Similarly, we can also use Union for typing
from typing import Type, Union
class Foo:
pass
class Bar:
pass
def func(is_bar: bool) -> Union[Type[Foo], Type[Bar]]:
if is_bar:
return Bar
else:
return Foo
Knowing the value of is_bar, it would be totally reasonable to use assertions after calling func for type narrowing.
However, assertions do not seem to work at all for MyType as mypy is giving an error for the following code example:
MyType = func(True)
assert MyType is Bar
# `assert MyType is Type[Bar]` gives the same result
Test: Bar = MyType # Incompatible types in assignment (expression
# has type "Union[Type[Foo], Type[Bar]]",
# variable has type "Bar")
cast and isinstance do not work either.
MyType = func(True)
cast(Type[Bar], MyType)
Test: Bar = MyType # MyType is considered `Type[Bar] | Type[Foo]`
MyType = func(True)
assert isintance(MyType, Type[Bar])
Test: Bar = MyType # MyType is considered `Type[Bar] | Type[Foo]`
My questions is: how to do type narrowing for the types of types? Or is it a limitation of mypy? If that's so, what would be the workaround?
Related: