与 Union 元素不兼容的类型
Incompatible type with element of Union
我最近收到了这个 受雇于以下职位:
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).')
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"
Found 1 error in 1 file (checked 1 source file)
为了避免类似的 mypy 错误,我一直使用注释掉的两个习语之一。
还有其他解决方案吗?
为什么不使用 Default
class 的实例而不是 class 本身? MyPy understands isinstance
并且可以推断其中使用的对象类型,这与使用 is
.
的类型缩小形成对比
至于使用 class 的实例作为参数的默认值:根据 Python 文档的 function definition 部分,没有显着的开销并且它可以忽略:
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.
例如:
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, Default] = Default()):
if isinstance(ham, Default):
ham = ['prosciutto', 'jamon']
if ham is None:
print('Eggs?')
else:
print(str(len(ham)) + ' ham(s).')
我最近收到了这个
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).')
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"
Found 1 error in 1 file (checked 1 source file)
为了避免类似的 mypy 错误,我一直使用注释掉的两个习语之一。
还有其他解决方案吗?
为什么不使用 Default
class 的实例而不是 class 本身? MyPy understands isinstance
并且可以推断其中使用的对象类型,这与使用 is
.
至于使用 class 的实例作为参数的默认值:根据 Python 文档的 function definition 部分,没有显着的开销并且它可以忽略:
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.
例如:
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, Default] = Default()):
if isinstance(ham, Default):
ham = ['prosciutto', 'jamon']
if ham is None:
print('Eggs?')
else:
print(str(len(ham)) + ' ham(s).')