Validate Python dataclass types
Table of contents
In Python you can create dataclasses
with the wrong type. The type checker should show an error, but nothing prevents creating the object. This small function validates that each attribute is of the correct type by using the __annotations__
attribute of the dataclass
. You can also create a base class to inherit from, but it won’t work if you override the __post_init__
method in the child classes.
import dataclasses
def val(t):
"""
Validate the object `t` types based on the
__annotations__ dictionary.
"""
for k,v in t.__annotations__.items():
assert isinstance(getattr(t, k), v)
#Base class
@dataclasses.dataclass(frozen=True, slots=True)
class Base:
def __post_init__(self):
val(self)
# Inherit from base class
@dataclasses.dataclass(frozen=True, slots=True)
class User(Base):
name: str
age: int
Now when initializing the object, it will throw a runtime exception if any of the attributes is not of the correct type.
# ok
u = User(name="ric", age=12)
# error
u = User(name=123, age=12)
Disclaimer
This is just a quick snipppet. I recommend using pydantic if you need a robust data validation library.