10

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]
pynista
  • 241
  • 5
  • 9
  • [Annotations can be any python expression](https://docs.python.org/3/reference/simple_stmts.html#annassign). What do you mean by "safely"? – Patrick Haugh Apr 02 '19 at 14:33
  • The documentation for the `dataclasses` module and various tutorials on the Internet use only "simple" types, such as `str`, `float`, `int`, SomeClass, `Any`. – pynista Apr 02 '19 at 15:46
  • As a side note, if you want to verify that your type hints are correct, you should use a type checker, like [mypy](http://mypy-lang.org/), [pyre](https://github.com/facebook/pyre-check) or [pyright](https://github.com/Microsoft/pyright). – Arne Apr 05 '19 at 10:17

1 Answers1

4

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.

Arne
  • 17,706
  • 5
  • 83
  • 99