typehints -> None or leave blank

馋奶兔 提交于 2020-06-11 18:17:31

问题


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

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

i.e.

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

def no_hint(p:str):
    pass

And which PEP addresses this?


回答1:


Be explicit and always include -> None for functions that return 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 - Type Hints indirectly addresses this:

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.



来源:https://stackoverflow.com/questions/48223558/typehints-none-or-leave-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!