擅长:python、mysql、java
<p>正如deceze在评论中所说的,你的代码确实是不健全的。如果有人要做下面的事呢?在</p>
<pre><code># 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
</code></pre>
<p>如果您想让mypy理解您的union当前正好是一个列表,那么您需要通过执行isinstance检查或类似操作来缩小变量的类型。在</p>
^{pr2}$
<p>或者更好的方法是重新设计代码,这样就不需要联合开始,只需要一个<code>List[int]</code>。在大多数情况下,尽量减少联合类型的使用是一个好主意,经常这样做(尽管不总是!)最终使您的代码更简单、更易于理解。在</p>