如何键入提示函数的可选 return 参数?

How to type hint a function's optional return parameter?

如何键入提示可选输出参数:

def myfunc(
        x: float, 
        return_y: bool = False
        ) -> float, Optional[float] : # !!! WRONG !!!

    # ... code here
    #
    # y and z are floats

    if return_y:
        return z, y

    return z

--- 编辑

这似乎有效:
-> Tuple[float, Union[None, float]] :

但这太丑陋了,似乎掩盖了通常它只会 return 一个简单的浮点数这一事实。 这是正确的方法吗?

请参阅下面的答案以了解正确的方法。


注意:这种设计不是一个好的做法,应该避免使用一致的 return 类型。不过,如果必须这样做, 可选输出参数 表示根据输入参数的标志可能不会 return 编辑的参数。

Python 3.10PEP 604 您现在可以使用 | 而不是 Union

return 类型为 float | Tuple[float, float]


正确的类型提示是:

from typing import Tuple, Union


def myfunc(x: float, return_y: bool = False) -> Union[float, Tuple[float, float]]:
    z = 1.5

    if return_y:
        y = 2.0
        return z, y

    return z

但是,拥有这些 return 通常不是一个好习惯。要么return类似Tuple[float, Optional[float]],要么写多个函数,以后会好办多了。

关于 return 语句一致性的更多信息:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).

  • Why should functions return values of a consistent type?