You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As mypy understands isinstance checks, I wondered if I can use this to mimic GADT (Generalized algebraic data type) in functional languages such as Haskell and OCaml.
I tried to mimic following Haskell code
dataExprawhereConst::a->ExpraAdd::ExprInt->ExprInt->ExprInteval::Expra->a
eval (Const x) = x
eval (Add a b) = eval a + eval b
But in the elif isinstance(e, Add) branch the type of e is inferred as '<nothing>' causing type errors.
As '<nothing>' is not documented (c.f. #3030), I'm not sure if this is intended behavior. So I report it here just in case, though the attempt is just out of curiosity.
In the example below of the same bug, after the isinstance(obj, SubclassA) check, obj is inferred to be <nothing>.
from typing import Generic, Optional, TypeVar
T = TypeVar("T")
class BaseClass(Generic[T]):
def __init__(self, item: T) -> None:
self.item: T = item
class SubclassA(BaseClass[int]):
pass
def generic_func(obj: BaseClass[T]) -> Optional[T]:
if isinstance(obj, SubclassA):
return obj.item
# error: Returning Any from function declared to return "Optional[T]"
# error: <nothing> has no attribute "item"
return None
Activity
cpeisert commentedon Jan 8, 2021
In the example below of the same bug, after the
isinstance(obj, SubclassA)check,objis inferred to be<nothing>.pdarragh commentedon May 3, 2021
I also ran into this recently. From some more playing around with it, it seems like there's an issue when:
My minimal examples to show this:
There may be other cases (like methods in subclasses), but I didn't check them.
noudin-ledger commentedon Jun 7, 2023
Still opened and still an issue, I'd love being able to mimick GADTs in python
ichard26 commentedon Aug 22, 2023
While this issue came before, I'm closing this in favour of #12949 which describes the same bug in a much simpler way. Thanks for reporting!