[英]Why PyPy fails when I try to define type annotated class member (e.g. list or dict)?
I have following simple code:我有以下简单代码:
from dataclasses import dataclass, field
@dataclass
class Test:
names: list[str] = field(default_factory=list)
if __name__ == '__main__':
Test(['a', 'b', 'c'])
Trying to execute it with latest PyPy available via pyenv
at the moment:目前正在尝试通过pyenv
使用最新的 PyPy 来执行它:
Python 3.8.12 (9ef55f6fc369, Oct 24 2021, 20:11:54)
[PyPy 7.3.7 with GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]
I receive following error:我收到以下错误:
Traceback (most recent call last):
File "test.py", line 4, in <module>
@dataclass
File "test.py", line 6, in Test
names: list[str] = field(default_factory=list)
AttributeError: type object 'list' has no attribute '__class_getitem__'
Same happens basically with any iterable type, eg dict[str, str]
etc. Any ideas?基本上任何可迭代类型都会发生同样的情况,例如dict[str, str]
等。有什么想法吗?
Use of list
in that way was only introduced in Python 3.9.以这种方式使用list
仅在 Python 3.9 中引入。 See PEP-585 for more information.有关详细信息,请参阅PEP-585 。 Prior to that you had to import List
from the typing
module to use for type hints (unless you just wanted to specify list
without the contained type).在此之前,您必须从typing
模块导入List
以用于类型提示(除非您只想指定不包含类型的list
)。
This means your example would need to be:这意味着您的示例需要是:
from dataclasses import dataclass, field
from typing import List
@dataclass
class Test:
names: List[str] = field(default_factory=list)
if __name__ == '__main__':
Test(['a', 'b', 'c'])
Alternatively you can import annotations
from __future__
and gain the ability to parameterise list
when using it in a type hint.或者,您可以从__future__
导入annotations
,并在类型提示中使用它时获得参数化list
的能力。 Note that this does depend in your tools recognising it as valid and I don't use it personally so I can't guarantee there aren't problems, as per the comments.请注意,这确实取决于您的工具是否将其识别为有效,并且我个人不使用它,因此根据评论,我不能保证没有问题。
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class Test:
names: list[str] = field(default_factory=list)
if __name__ == '__main__':
Test(['a', 'b', 'c'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.