【问题标题】:Tuple[Any] does not satisfy Type[Any]Tuple[Any] 不满足 Type[Any]
【发布时间】:2021-08-07 19:26:37
【问题描述】:

我注意到Tuple[Any] 不满足Type[Any]。

在python3.8中...

var: Type[Any] = Tuple[Any]

当我对此运行 mypy 时,我得到了

Incompatible types in assignment (expression has type "object", variable has type "Type[Any]")

有人知道我在这里做错了什么吗?我的最终目标是能够将var 分配给Tuple[Any, ...]。

谢谢!

【问题讨论】:

    标签: python type-hinting python-typing


    【解决方案1】:

    虽然Tuple[Any] 是静态类型系统中Any 的子类型,但Type[Any] 的唯一有效值是实际的运行时 类型,即type 类型的对象。您可以将tuple 分配给var,但不能分配Tuple[Any],因为Tuple[Any] 不是type。

    【讨论】:

      【解决方案2】:

      Tuple 类型提示 不等同于tuple 类型 本身。比较他们的行为:

      >>> from typing import Tuple
      >>> tuple()
      ()
      >>> Tuple()
      TypeError: Type Tuple cannot be instantiated; use tuple() instead
      

      因此,只有var: Type = tuple 有效,但var: Type = Tuple 的任何变体均无效。


      从 Python3.9 开始,builtin types and their type hints are unified。这允许两者互换使用:

      >>> tuple[int]()
      ()
      

      您可以期望var: Type = tuple[int] 工作一次mypy PEP 585 support is complete。

      【讨论】:

        猜你喜欢
        • 2020-02-24
        • 2020-07-07
        • 2020-10-25
        • 2019-12-18
        • 2021-03-17
        • 2019-09-08
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        相关资源
        最近更新 更多