2

I am using the new dataclass feature of Python3 that allows specifying the type of the class fields. In this examples field2 should be of type List[int], and I passed a List[str] to it. This code runs without failure, I am wondering if there is an (automatic) way to have the code fail (i.e. using asserts, etc.) if the wrong type is passed to the class.

from dataclasses import *
import typing
@dataclass
class C:
    field1: str
    field2: typing.List[int]

if __name__ == '__main__':
    x = C('a',['a','b'])
    print(repr(x))
motam79
  • 3,542
  • 5
  • 34
  • 60
  • I created a tiny Python library for this purpose: https://github.com/tamuhey/dataclass_utils This library can be applied for such dataclass that holds another dataclass (nested dataclass), and nested container type (like `Tuple[List[Dict...`) – tamuhey Feb 08 '21 at 03:10

1 Answers1

3

Dataclasses use type hints, which are not checked at runtime. They can be checked with static type analysis tools such as mypy.

Dataclasses are not intended to provide runtime type-checked fields. You are just defining fields for a generated class, and the type hinting syntax makes it easy to do so and also provide type hints.

If you only use the type hints and not use a type checker tool such as mypy, you at least now documented the expected types. Also, some Python IDEs such as PyCharm and WingIDE can provide smarter auto-complete hints with this information.

I'd not try to enforce the type hint at runtime, even though technically you could implement such functionality. You really don't want to have to test every single element in a list to see if any of them are not integers. That's just a waste of CPU time, where you really just want to write code that doesn't produce such an invalid list in the first place. Static type checking aims to give you the latter without runtime cost.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343