PEP484类型提示--如何使用NoReturn类型注释可调用对象?

5

能否使用NoReturn类型注释Callable

我期望的方式会产生错误:

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
编辑:对于将来遇到此问题的任何人,问题是Python 3.7.0中的一个错误,升级到Python 3.7.2可以缓解此问题。

这可能与Python问题34921有关,该问题已在Python 3.7.2中修复。该问题中的重现情况不同,但潜在原因可能相同。 - user2357112
1个回答

2

对于我来说(使用Python 3.7.2),它可以正常工作,没有错误:

最初的回答

>>> from sys import exit
>>> from typing import Callable, NoReturn
>>> f: Callable[..., NoReturn] = exit
>>>

Mypy 是否正确处理它?我看到提问者的错误消息来自尝试运行代码,而不是尝试在代码上运行 mypy,但 mypy 的处理也很重要。 - user2357112
在我的情况下,mypy正确地没有抱怨这个。 - Querenker
4
已升级3.7.0 -> 3.7.2,现在能正常工作了!太棒了。 - user3831357

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接