类型提示 ->无或留空 [英] typehints -> None or leave blank

查看:42
本文介绍了类型提示 ->无或留空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using python 3, one has the option to use typehints.

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

My question is, if a function returns None, should one add this, or leave it blank.

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

def no_hint(p:str):
    pass

哪个 PEP 解决了这个问题?

And which PEP addresses this?

推荐答案

明确并始终包含 ->None 对于返回 None

Be explicit and always include -> None for functions that return None

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

That's because otherwise, for functions that don't take arguments, the type checker will assume that you did not use type hints at all. For example, is def foo(): going to return None, or was it simply not type hinted?

PEP 484 - 类型提示间接地址这个:

PEP 484 - Type Hints indirectly addresses this:

注意__init__的返回类型应该用->注释;无.这样做的原因很微妙.如果 __init__ 假定返回注释 ->无,这是否意味着无参数、未注释的 __init__ 方法仍应进行类型检查?与其让这个模棱两可或在异常中引入异常,我们只是说 __init__ 应该有一个返回注释;因此,默认行为与其他方法相同.

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.

这篇关于类型提示 ->无或留空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆