6

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 TypeVars, but I couldn't figure out what would be the right thing to bind T to in this case.

Luiz Scheidegger
  • 788
  • 5
  • 12
  • 1
    Does this answer your question? [Exclude type in Python typing annotation](https://stackoverflow.com/questions/57854871/exclude-type-in-python-typing-annotation) – jirassimok Nov 09 '19 at 00:44

0 Answers0