I am creating new data class in python.
@dataclass
class User(Mixin):
id: int = None
items: List[DefaultItem] = None
This items is array of DefaultItem objects but I need this to be multiple possible objects like:
items: List[DefaultItem OR SomeSpecificItem OR SomeOtherItem] = None
How can I do something like this in python?
>Solution :
You can use typing.Union for this.
items: List[Union[DefaultItem, SomeSpecificItem, SomeOtherItem]] = None
And if you are on Python 3.10, they’ve added a convenient shorthand notation:
items: list[DefaultItem | SomeSpecificItem | SomeOtherItem] = None
Also just as a note: If items is allowed to be None, you should mark the type as Optional.