gpt4 book ai didi

python - 输入提示返回,返回无,根本不返回?

转载 作者:行者123 更新时间:2023-12-03 15:48:02 25 4
gpt4 key购买 nike

这三个函数的返回类型提示有什么区别吗?

def my_func1():
print("Hello World")
return None

def my_func2():
print("Hello World")
return

def my_func3():
print("Hello World")
如果他们都有 -> None返回类型提示,因为那是他们实际上显式或隐式返回的内容?还是应该 my_func2my_func3字面上没有返回类型提示?
询问的动机是 this question , 和 this nice answer ,以及我正在学习的事实 Type Hints .

最佳答案

他们都应该有 -> None返回类型,因为它们都明确返回 None .
请注意,还有 typing.NoReturn 输入实际上从不返回任何内容的函数,例如

from typing import NoReturn

def raise_err() -> NoReturn:
raise AssertionError("oops an error")
其他类型的函数(由 @chepner 指出)实际上永远不会返回,因此应该用 -> NoReturn 类型提示例如,一个仅使用 sys.exit 结束的事件循环或任何 os.exec* 职能

Or should my_func2 or my_func3 have literally no return type hint?


在我看来,他们应该总是有一个类型提示,因为作为 @yedpodtrzitkotheir answer 中说, 没有类型提示的函数在默认情况下不会由 mypy 进行类型检查,并且它们的返回值基本上被视为它们将被输入为 Any .这大大减少了类型检查的好处,这也是我总是使用 mypy 设置 disallow_untyped_defs = True 的原因之一。用于新项目。

关于python - 输入提示返回,返回无,根本不返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64063732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com