Is it possible to require a TypeVar
in mypy to only resolve to non-Optional
types? E.g.
from typing import Callable, Optional, TypeVar
from typing_extensions import Protocol
T = TypeVar('T')
def mapper(callabl: Callable[..., T]) -> T:
return callabl()
def bad_function() -> Optional[int]:
return None
mapper(reveal_type(bad_function))
In this example, bad_function
is revealed to be of type def () -> Union[builtins.int, None]
. I would like a way to restrict T
to be bound to any type that's not optional (that is, not a Union
with None
), such that this code snippet would fail to type check. Other checkers like Typescript (and Kotlin's builtin type system) support this by default so I was wondering if it's possible to do in mypy as well. I know that it's possible to bind TypeVar
s, but I couldn't figure out what would be the right thing to bind T
to in this case.