【问题标题】:What is canonical way to type empty __slots__?输入空 __slots__ 的规范方法是什么?
【发布时间】:2021-03-28 05:34:02
【问题描述】:

如果我输入插槽:

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[&lt;nothing&gt;, ...] 中的 mypy 是什么意思?元组是不可变的,所以肯定一个空元组不应该是......可变数量的无......?

【问题讨论】:

  • 更重要的是:为什么你想这样做? __slots__ = () 将被正确推断。
  • 啊——对……我以为() 和tuple() 是一回事。

标签: mypy slots


【解决方案1】:

问题不在于注解,而在于值。使用 literal 元组明确表示固定大小的元组,包括空元组:

class Foo:
    __slots__: Tuple[()] = ()

请注意,即使没有注释,MyPy 也会正确推断此 __slots__ 的类型。


callable tuple 的返回类型为 Tuple[T, ...],因为对于大多数输入,输出长度是未知的。 The call tuple() is not special cased. 与 tuple() 一样,从 there is no type inhabiting T – its type is &lt;nothing&gt; 推断 T 没有任何价值。

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 2012-02-08
    • 2018-01-27
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多