I want to use the Union
and Optional
types when creating a dataclass.
Can I use these types safely?
E.g.:
@dataclass
class Car:
year: int
owner: Optional[str]
engine: Union[Engine1, Engine2]
I want to use the Union
and Optional
types when creating a dataclass.
Can I use these types safely?
E.g.:
@dataclass
class Car:
year: int
owner: Optional[str]
engine: Union[Engine1, Engine2]
Yes you can. First off, annotations in python don't do anything by themselves. From other languages you might expect that declaring a variable as int
will lead to an error if it is instantiated as, say, a string, but that just isn't the case in python.
Annotations are only used by third party libraries or tools, like your IDE when it gives you hints, or mypy
when it does a static type analysis of your code.
So you should use a kind of annotation that your tools work well with, and from my personal experience that would mean to use the type annotations from the typing
module over the basic types.
While there is no declarative statement on what you must use, here is a thread discussing default dataclass types including ericvsmith (the author of the dataclasses module) and gvanrossum (the author of python), and they agree that typing.Any
should be preferred over object
.
I assume the dataclass documentation uses basic python types in order to not place too much of a burden of knowledge on the reader. You can use dataclasses just fine without knowing anything about the typing
module after all, and once you are comfortable with how dataclasses work, you're probably going to run into and appreciate the additional power of using typing
's annotations anyway.