12

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]
ruohola
  • 21,987
  • 6
  • 62
  • 97
Denis Sologub
  • 7,277
  • 11
  • 56
  • 123
  • 1
    `my_array: list`? Or `List[...]` if you want to specify the element type. But you'll have to import those things from the right places - `dataclass` isn't in `abc`. – jonrsharpe Aug 28 '19 at 10:55

1 Answers1

37

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]
ruohola
  • 21,987
  • 6
  • 62
  • 97