假设我在控制台脚本 (1) 中有以下函数:
def example(x: int) -> typing.Union[typing.NoReturn, int]:
if x > 10: # something is wrong, if this condition is true
# logging
# cleanup
sys.exit()
return x * 10
返回类型是否正确指定?由于 NoReturn 意味着该函数never回报(参见:https://docs.python.org/3/library/typing.html),这似乎是错误的。但 mypy 并不抱怨以下组合Union
and NoReturn
.
这似乎是错误的(2),因为SystemExit
没有返回,而是由sys.exit
(并导致 mypy 错误):
def example(x: int) -> Union[SystemExit, int]:
...
那么(3)呢:
def example(x: int) -> Union[SystemExit, int]:
if x > 10: # something is wrong, if this condition is true
# logging
# cleanup
return sys.exit()
return x * 10
这似乎也有道理(4)。然而,签名隐藏了特殊行为:
def example(x: int) -> int:
if x > 10: # something is wrong, if this condition is true
# logging
# cleanup
sys.exit()
return x * 10
NoReturn
用于声明该函数never返回。
如果我们注释为NoReturn
所有可能不返回控制的函数,这将适用于所有可能引发异常的函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)