假设我有一个Foo对象,它有多个字段,可以是None,也可以是其他类型的。字段是否为None关系到其他字段是否为None,因此,通过检查一个字段,我可以立即知道其他字段是否为None。
我知道这是糟糕的类设计,但是我无法修改它,因为我正在注释的是其他人的代码。
看起来,在佩普647中引入的佩普647是我添加此功能的最佳选择,但我不知道如何将它们具体应用于这种情况。我附加了一个使用子类的尝试,但是它在MyPy和Pyright中都失败了。
from typing import Optional
from typing_extensions import TypeGuard
class Foo:
"""A class containing the parameters `value`, `values` and `other`. If
`values` is `None` then both the others are not, and if the others are not
then `values` is.
"""
def __init__(self, value: 'int | list[int]', other: Optional[int]) -> None:
is_singular = isinstance(value, int)
self.value = value if is_singular else None
self.values = None if is_singular else value
if is_singular:
assert other is not None
else:
assert other is None
self.other = other
class SingularFoo(Foo):
"""A subclass for an instance of `Foo` where `values` is `None`
"""
def __init__(self, value: int, other: int) -> None:
super().__init__(value, other)
class MultiFoo(Foo):
"""A subclass for an instance of `Foo` where `values` is not `None`
"""
def __init__(self, value: list[int]) -> None:
super().__init__(value, None)
def isFooSingular(f: Foo) -> TypeGuard[SingularFoo]:
"""A type guard that returns whether `f` is singular (meaning that `values`
is `None` and `value` and `other` are not)
"""
return f.value is not None
# Create a singular `Foo`
my_foo = Foo(1, 2)
# Type guard
assert isFooSingular(my_foo)
# After the type guard, both should be considered as `int`
#
# Errors from MyPy:
# * Unsupported operand types for + ("int" and "None")
# * Unsupported operand types for + ("List[int]" and "int")
# * Unsupported operand types for + ("List[int]" and "None")
# * Unsupported operand types for + ("None" and "int")
# * Unsupported left operand type for + ("None")
print(my_foo.value + my_foo.other)如何修改此代码以使类型保护执行所需的类型缩小操作。
发布于 2022-02-20 13:29:41
如果您明确地了解了SingularFoo中的类型,该怎么办?这似乎让mypy感到高兴:
class SingularFoo(Foo):
"""A subclass for an instance of `Foo` where `values` is `None`"""
value: int
other: int
def __init__(self, value: int, other: int) -> None:
super().__init__(value, other)https://stackoverflow.com/questions/71194509
复制相似问题