返回类型:如果在函数中对sys.exit()进行条件调用



假设我在控制台脚本(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意味着函数从不返回(参见:https://docs.python.org/3/library/typing.html),这似乎是错误的。但mypy并不抱怨UnionNoReturn的结合。

这似乎是错误的(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

这似乎也是合理的。然而,签名隐藏了特殊行为:

def example(x: int) -> int:
if x > 10: # something is wrong, if this condition is true
# logging
# cleanup
sys.exit()
return x * 10

NoReturn用于声明函数从不返回

如果我们将所有可能不返回控制的函数注释为NoReturn,这将适用于所有可能引发异常的函数。

如果不是在示例函数内部调用sys.exit((,而是在外部调用它,会怎么样

def example(x: int) -> int:
if x > 10: # something is wrong, if this condition is true
# logging
# cleanup
return [] # or x = []
return x * 10

然后在你的代码

if x==[]:
sys.exit()

最新更新