Ben*_*Ben 2 python python-typing
是否可以在 python 中编写一个 typehint 来保证 ifNone被赋予函数然后None返回?
例如,这是可能的:
\nfrom 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)\nRun Code Online (Sandbox Code Playgroud)\n但即使我知道参数有值,类型签名也不能保证输出有值。例如:
\ndef printer(msg: str):\n print(msg)\n\ndata = {\'a\': \'a\'}\nresult = getMaybe(data, \'a\')\nprinter(result)\nRun Code Online (Sandbox Code Playgroud)\n给出错误:
\nerror: 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)\nRun Code Online (Sandbox Code Playgroud)\n是否可以在类型签名中进行编码,当None作为参数给出时,然后None返回?
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)