Return 类型:如果在函数中有条件地调用 sys.exit()

Return Type: If conditional call to sys.exit() in function

假设我在控制台脚本 (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

是否正确指定了return类型?由于 NoReturn 意味着函数 never returns (cf.: https://docs.python.org/3/library/typing.html),这似乎是错误的。但是 mypy 不会抱怨 UnionNoReturn.

的组合

这似乎是错误的 (2),因为 SystemExit 不是 returned,而是由 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

如果不是在示例函数内部调用 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()

NoReturn 用于声明函数 never returns.

如果我们将所有可能无法 return 控制的函数注释为 NoReturn,这将适用于所有可能抛出异常的函数。