目前,当我无法在函数签名中分配默认参数和/或已经具有含义时,我会使用此策略。None
from typing import Optional
DEFAULT = object()
# `None` already has meaning.
def spam(ham: Optional[list[str]] = DEFAULT):
if ham is DEFAULT:
ham = ['prosciutto', 'jamon']
if ham is None:
print('Eggs?')
else:
print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)
错误:
Failed (exit code: 1) (2607 ms)
main.py:7: error: Incompatible default for argument "ham" (default has type "object", argument has type "Optional[List[str]]")
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
ham
而不出现错误?或者DEFAULT = object() …
我最近收到了这个很好的答案,用于以下方面:
from typing import Union, cast
class Default:
"""Placeholder for default arguments."""
# ham[] is mutable. `None` has meaning (or is not preferred).
def spam(ham: Union[list[str], None, type[Default]] = Default):
if ham is Default:
ham = ['prosciutto', 'jamon']
#ham = cast(Union[list[str], None], ham)
#assert isinstance(ham, (list, type(None)))
if ham is None:
print('Eggs?')
else:
print(str(len(ham)) + ' ham(s).')
Run Code Online (Sandbox Code Playgroud)
mypy错误:
Failed (exit code: 1) (2655 ms)
main.py:17: error: Argument 1 to "len" has incompatible type "Union[List[str], Type[Default]]"; expected "Sized" …
Run Code Online (Sandbox Code Playgroud)