Skip to content
Advertisement

PEP484 typing — how to annotate Callable with NoReturn type?

Is it possible to annotate Callable with the NoReturn type?

The way I would expect to do this yields an error:

from sys import exit
from typing import Callable, NoReturn

f: Callable[..., NoReturn] = exit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 755, in __getitem__
    return self.__getitem_inner__(params)
  File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 251, in inner
    return func(*args, **kwds)
  File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 774, in __getitem_inner__
    result = _type_check(result, msg)
  File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/typing.py", line 135, in _type_check
    raise TypeError(f"Plain {arg} is not valid as type argument")
TypeError: Plain typing.NoReturn is not valid as type argument

Edit: for anyone who encounters this problem in the future, the issue was a bug in Python 3.7.0 and upgrading to Python 3.7.2 mitigates the issue.

Advertisement

Answer

For me (with Python 3.7.2) it works without an error:

>>> from sys import exit
>>> from typing import Callable, NoReturn
>>> f: Callable[..., NoReturn] = exit
>>>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement