如何解决Python 输入,如果没有给出返回无
是否可以在 python 中编写一个类型提示来保证 None
被赋予一个函数然后返回 None
?
例如这是可能的:
from typing import Dict,Union
def getMaybe(dictionary: Optional[Dict],key: str) -> Optional[str]:
if dictionary is None:
return dictionary
return dictionary.get(key)
但是即使我知道参数有值,类型签名也不能保证输出。例如:
def printer(msg: str):
print(msg)
data = {'a': 'a'}
result = getMaybe(data,'a')
printer(result)
给出错误:
error: Argument of type "str | None" cannot be assigned to parameter "msg" of type "str" in function "printer"
Type "str | None" cannot be assigned to type "str"
Type "None" cannot be assigned to type "str" (reportGeneralTypeIssues)
是否可以在类型签名中编码,当 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。