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:
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'])