gpt4 book ai didi

python - typehints -> None 或留空

转载 作者:太空狗 更新时间:2023-10-29 21:33:22 25 4
gpt4 key购买 nike

使用 python 3,可以选择使用类型提示。

我的问题是,如果一个函数返回 None,应该添加它还是留空。

def hint(p:str) -> None:
pass

def no_hint(p:str):
pass

哪个 PEP 解决了这个问题?

最佳答案

要明确,并且始终为返回 None

的函数包含 -> None

因为否则,对于不带参数的函数,类型检查器会假定您根本没有使用类型提示。例如,def foo(): 是要返回 None,还是只是没有类型提示?

PEP 484 - Type Hints间接解决了这个问题:

Note that the return type of __init__ ought to be annotated with -> None. The reason for this is subtle. If __init__ assumed a return annotation of -> None, would that mean that an argument-less, un-annotated __init__ method should still be type-checked? Rather than leaving this ambiguous or introducing an exception to the exception, we simply say that __init__ ought to have a return annotation; the default behavior is thus the same as for other methods.

关于python - typehints -> None 或留空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48223558/

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