python - 我可以使用 typing_extensions 中的实验类型吗?

标签 python python-typing

更具体地说:

解决类似 How do I type hint a method with the type of the enclosing class? 的问题
PEP 673引入了 typing.Self。 PEP 是一个草案,但它目前是 typing_extensions 4.0.0 中的实验类型

我尝试在 python 3.8 中使用它

@dataclasses.dataclass
class MenuItem:
    url: str
    title: str
    description: str = ""
    items: typing.List[typing_extensions.Self] = dataclasses.field(default_factory=list)

但它提高了

TypeError: Plain typing_extensions.Self is not valid as type argument

我可以只使用文字字符串“MenuItem”。但我想知道为什么这不起作用。

最佳答案

是的,你可以,但要注意包的用途:

The typing_extensions module serves two related purposes:

  • Enable use of new type system features on older Python versions. For example, typing.TypeGuard is new in Python 3.10, but typing_extensions allows users on previous Python versions to use it too.
  • Enable experimentation with new type system PEPs before they are accepted and added to the typing module.

这个具体案例是 bug in typing_extensions .这是 planned to get fixed in 4.0.1 .

关于python - 我可以使用 typing_extensions 中的实验类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70083371/

相关文章:

python - 调用Python脚本时, "./script.py"和 "python script.py"有什么区别

python - 计算 DataFrame 中列中的单词

python - 根据 Pandas 中的字符串用 NaN 替换列

python - python中多个泛型协议(protocol)的输入输出如何使用TypeVar?

没有循环导入的 Python 类型提示

python - 如何在 macOS Big Sur 上的 Python 2.7 中安装 pip?

python - 从 0-d numpy 数组中恢复字典

python - 如何生成具有给定限制和平均值的随机数?

python - 如何在协议(protocol)上制作 "isinstance"还包括函数签名和数据类型?

python - 在 Pycharm 中对类装饰属性进行类型检查