Python 输入,如果 none 给出 return none
Python typing, if none is given return none
是否可以在 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
是否可以在 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