Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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, e.g. dict[str, str] etc. Any ideas?

>Solution :

Use of list in that way was only introduced in Python 3.9. See PEP-585 for more information. 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).

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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading