Search code examples
python-3.xooppython-3.7

How to validate typing attributes in Python 3.7


I want to validate since the instance creation if the type is right or wrong, i tried using @dataclass decorator but doesn't allow me to use the __init__ method, i also tried using a custom like class type

also in order of the type made some validations (if is a int, that field>0 or if is a str clean whitespaces, for example), i could use a dict to validate the type, but i want to know if there's a way to do it in pythonic way

class Car(object):
    """ My class with many fields """

    color: str
    name: str
    wheels: int

    def __init__(self):
        """ Get the type of fields and validate """
        pass

Solution

  • You can use the __post_init__ method of dataclasses to do your validations.

    Below I just confirm that everything is an instance of the indicated type

    from dataclasses import dataclass, fields
    
    def validate(instance):
        for field in fields(instance):
            attr = getattr(instance, field.name)
            if not isinstance(attr, field.type):
                msg = "Field {0.name} is of type {1}, should be {0.type}".format(field, type(attr))
                raise ValueError(msg)
    
    @dataclass
    class Car:
        color:  str
        name:   str
        wheels: int    
        def __post_init__(self):
            validate(self)