更具体地说:
解决类似 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, buttyping_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/