How to declare an array or a list in a Python @dataclass?

11,816

There is no Array datatype, but you can specify the type of my_array to be typing.List:

from dataclasses import dataclass
from typing import List

@dataclass
class Test:
    my_array: List[ChildType]

And from Python 3.9 onwards, you can conveniently just use list:

from dataclasses import dataclass

@dataclass
class Test:
    my_array: list[ChildType]
Share:
11,816
Denis Sologub
Author by

Denis Sologub

There's got to be a text where I tell what a steep dude I am

Updated on July 28, 2022

Comments

  • Denis Sologub
    Denis Sologub almost 2 years

    How can I declare an array (or at least list) in @dataclass? A something like below:

    from dataclasses import dataclass
    
    @dataclass
    class Test():
        my_array: Array[ChildType]