简体   繁体   English

为什么当我尝试定义带注释的类型 class 成员(例如列表或字典)时 PyPy 失败?

[英]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.

相关问题 有条件地定义属性(使用装饰器)(例如,try / except?) - define property (with decorator) conditionally (e.g. try/except?) 用固定键类型(例如Enum类型)实现字典的最佳方法? - Best way to implement a dict with a fixed key type (e.g. an Enum type)? 为什么分配给空列表(例如 [] = &quot;&quot;)不是错误? - Why isn't assigning to an empty list (e.g. [] = "") an error? 当变量应该设置为私有类变量(例如_var)vs类常量(例如VAR)vs私有类常量(例如_VAR)? - When a variable should be set as a private class variable (e.g. _var) vs a class constant (e.g. VAR) vs a private class constant (e.g. _VAR)? 如何访问 Python 超类的属性,例如通过 __class__.__dict__? - How to access properties of Python super classes e.g. via __class__.__dict__? 如何将字符串(例如'A')引用到更大列表的索引(例如['A','B','C','D',...])? - How can I reference a string (e.g. 'A') to the index of a larger list (e.g. ['A', 'B', 'C', 'D', ...])? 从我用来存储的对象类到“继承”的字典; 例如my_dict [&#39;item1&#39;]。method1()或mydict [&#39;item1&#39;]。property1 =&#39;new&#39; - Dictionary to “inherit” from class of objects that I use it to store; e.g. my_dict['item1'].method1() or mydict['item1'].property1 = 'new' 列表接受可迭代对象作为输入。 但是,当输入为int或float时,例如list(1),则不接受此输入。 为什么? - Lists accept iterable objects as inputs. However, when the input is an int or float, e.g. list(1), this is not accepted. Why? 在Python中使用Firebase-Admin解压缩AuthError(例如Dict) - Unpacking AuthError (to e.g. Dict) with Firebase-Admin in Python 定义适用于多个关键字(例如 Given、When 和 Then)的 Behave 步骤 - Define a Behave step that works for multiple keywords (e.g. Given, When, and Then)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM