键入空 __slots__(或空元组)的规范方法是什么?
What is the canonical way to type empty __slots__ (or empty tuple)?
如果我输入插槽:
class Foo:
__slots__: Tuple[()] = tuple()
然后,在严格模式下,mypy (0.812) 告诉我:
Incompatible types in assignment (expression has type "Tuple[<nothing>, ...]", variable has type "Tuple[]")
我会写:
__slots__: Tuple[()] = cast(Tuple[()], tuple())
但这很难看。这样做的规范方法是什么? Tuple[<nothing>, ...]
是什么意思?元组是不可变的,所以一个空元组肯定不应该是……一个什么都没有的变量……?
问题不在于注释,而在于值。使用 literal 元组来明确表示固定大小的元组,包括空元组:
class Foo:
__slots__: Tuple[()] = ()
请注意,即使没有注释,MyPy 也会正确推断出此 __slots__
的类型。
callable tuple
有一个 return 类型的 Tuple[T, ...]
,因为对于大多数输入来说,输出长度是未知的。 The call tuple()
is not special cased. As with tuple()
there is no value to infer T
from, there is no type inhabiting T
– its type is <nothing>
.
如果我输入插槽:
class Foo:
__slots__: Tuple[()] = tuple()
然后,在严格模式下,mypy (0.812) 告诉我:
Incompatible types in assignment (expression has type "Tuple[<nothing>, ...]", variable has type "Tuple[]")
我会写:
__slots__: Tuple[()] = cast(Tuple[()], tuple())
但这很难看。这样做的规范方法是什么? Tuple[<nothing>, ...]
是什么意思?元组是不可变的,所以一个空元组肯定不应该是……一个什么都没有的变量……?
问题不在于注释,而在于值。使用 literal 元组来明确表示固定大小的元组,包括空元组:
class Foo:
__slots__: Tuple[()] = ()
请注意,即使没有注释,MyPy 也会正确推断出此 __slots__
的类型。
callable tuple
有一个 return 类型的 Tuple[T, ...]
,因为对于大多数输入来说,输出长度是未知的。 The call tuple()
is not special cased. As with tuple()
there is no value to infer T
from, there is no type inhabiting T
– its type is <nothing>
.