[Python] How to cleanly add a validation function to a TypedDict

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I currently have a bunch of classes describing serializable data structures in python. Something like that :

    class Dummy(Serializable):
    def __init__(self, p_1: str, p_2: int) -> None:
    self.p_1 = p_1
    self.p_2 = p_2

    @classmethod
    def validate(cls, data: dict) -> Errors:
    validator = DataModelValidator({
    "p_1": data_is_type(str),
    "p_2": [
    data_is_type(int),
    data_less_than(10)
    ],
    }, exact=True)
    return validator.validate(data)


    Serializable and DataModelValidator are home-made classes used to handle and validate those structures.

    I would like to attempt to use TypedDict instead, something like that :

    class Dummy(TypedDict):
    p_1: str
    p_2: int

    def validate(self) -> Errors:
    validator = DataModelValidator({
    "p_1": data_is_type(str),
    "p_2": [
    data_is_type(int),
    data_less_than(10)
    ],
    }, exact=True)
    return validator.validate(data)



    as I feel this would be way cleaner. This is code used for testing, and I would like to use keep the IDE's auto-completion provided by the typing.

    However, I cannot attach a function to a TypedDict, as it is just a dict. I am looking for an idea to cleanly tie the dict and the validation function together.

    Continue reading...

Compartilhe esta Página