sha*_*unc 2 python tuples slots mypy python-typing
如果我输入插槽:
class Foo:
__slots__: Tuple[()] = tuple()
Run Code Online (Sandbox Code Playgroud)
然后,在严格模式下,mypy (0.812) 告诉我:
Incompatible types in assignment (expression has type "Tuple[<nothing>, ...]", variable has type "Tuple[]")
Run Code Online (Sandbox Code Playgroud)
我可以写:
__slots__: Tuple[()] = cast(Tuple[()], tuple())
Run Code Online (Sandbox Code Playgroud)
但这很丑陋。执行此操作的规范方法是什么?mypy 是什么意思Tuple[<nothing>, ...]?元组是不可变的,所以空元组肯定不应该是……没有任何变量的量……?
问题不在于注释,而在于值。使用文字元组明确表示固定大小的元组,包括空元组:
\nclass Foo:\n __slots__: Tuple[()] = ()\nRun Code Online (Sandbox Code Playgroud)\n__slots__请注意,即使没有注释,MyPy 也会正确推断出 this 的类型。
可调用函数的 返回tuple类型为Tuple[T, ...],因为对于大多数输入,输出长度未知。该调用tuple()没有特殊情况。由于tuple()没有可以推断的值T,因此 \xe2\x80\x93中没有类型,T它的类型是<nothing>。