Han*_*ans 2 python union list type-hinting mypy
myunionA可以是整数或整数列表。我如何编写类型提示来反映这一点?
它尝试了以下代码并使用 mypy 对其进行了测试。最后一行失败 - 请参阅错误文本。
numbers: List[int]
myunionA: Union[int, List[int]]
myunionB: Union[int, List[int]]
numbers = [11, 22]
numbers[2] = 3
myunionA = 2
myunionB[2] = 22 # ERROR(mypy): Unsupported target for indexed assignment
Run Code Online (Sandbox Code Playgroud)
如何编写一个类型提示,让我分配一个整数或一个整数列表?
正如 deceze 在评论中所说,您的代码确实不健全。如果有人要执行以下操作怎么办?
# Legal, since myunionB can be *either* int or List[int]
myunionB: Union[int, List[int]] = 99
# Boom! At runtime, we get a "int is not subscriptable" error
myunionB[2] = 22
Run Code Online (Sandbox Code Playgroud)
如果您希望 mypy 了解您的联合当前恰好是一个列表,您需要缩小执行 isinstance 检查等的变量类型。
if isinstance(myunionB, list):
# Type of myunionB is understood to be just List[int] here,
# so this type-checks
myunionB[2] = 22
else:
# And myunionB is understood to be just int here
myunionB = 100
# Alternatively, you can use an assert
assert isinstance(myunionB, list)
myunionB[2] = 22
Run Code Online (Sandbox Code Playgroud)
或者更好的是,重新设计你的代码,这样你就不需要从联合开始,让它只是一个List[int]. 在大多数情况下,尝试并尽量减少对 Union 类型的使用是一个好主意——经常这样做(尽管并非总是如此!)最终会使您的代码更简单、更易于理解。