Python 类型,如果没有给出则返回 none

Ben*_*Ben 2 python python-typing

是否可以在 python 中编写一个 typehint 来保证 ifNone被赋予函数然后None返回?

\n

例如,这是可能的:

\n
from typing import Dict, Union\ndef getMaybe(dictionary: Optional[Dict], key: str) -> Optional[str]:\n    if dictionary is None:\n        return dictionary\n\n    return dictionary.get(key)\n
Run Code Online (Sandbox Code Playgroud)\n

但即使我知道参数有值,类型签名也不能保证输出有值。例如:

\n
def printer(msg: str):\n    print(msg)\n\ndata = {\'a\': \'a\'}\nresult = getMaybe(data, \'a\')\nprinter(result)\n
Run Code Online (Sandbox Code Playgroud)\n

给出错误:

\n
error: Argument of type "str | None" cannot be assigned to parameter "msg" of type "str" in function "printer"\n \xc2\xa0Type "str | None" cannot be assigned to type "str"\n  \xc2\xa0\xc2\xa0Type "None" cannot be assigned to type "str" (reportGeneralTypeIssues)\n
Run Code Online (Sandbox Code Playgroud)\n

是否可以在类型签名中进行编码,当None作为参数给出时,然后None返回?

\n

ale*_*ame 5

typing.overload是你想要的:

from typing import Dict, Union, Optional, overload

@overload
def getMaybe(dictionary: None, key: str) -> None: ...

@overload
def getMaybe(dictionary: Dict, key: str) -> str: ...
    
def getMaybe(dictionary: Optional[Dict], key: str) -> Optional[str]:
    if dictionary is None:
        return dictionary

    return dictionary.get(key)
    

reveal_type(getMaybe(None, "")) # None
reveal_type(getMaybe({}, "")) # str
Run Code Online (Sandbox Code Playgroud)