python - How to cleanly add a validation function to a TypedDict - Stack Overflow

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

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.

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.

Share Improve this question edited Mar 24 at 17:31 InSync 11.1k4 gold badges18 silver badges56 bronze badges asked Mar 24 at 15:27 dododingodododingo 9911 bronze badges 4
  • Depends on how clean is "cleanly". Anything else than an annotation in a TypedDicts body is not allowed from a typing perspective, as it only a structural type. It will not fail at runtime though as long as you access the classmethod from the class Dummy.validate. It will work, but as it is not clean, as instances only seemingly have the function validate. – Daraan Commented Mar 24 at 16:31
  • Maybe you want to use a dataclass, some things will be easier with them others might involve more work. – Daraan Commented Mar 24 at 16:32
  • 5 The pydantic library can do such kind of validation for you (and much more). So i suggest to use it instead of inventing something similar. – Mullo Commented Mar 24 at 16:40
  • 3 This is precisely what pydantic is for. You should seriously consider using pydantic instead of implementing this behaviour yourself, unless you're consciously trying to implement such behaviour as a learning exercise. – Vin Commented Mar 24 at 18:03
Add a comment  | 

1 Answer 1

Reset to default 1

You're trying to implement something that has already been solved by Pydantic. This library is specifically designed for data validation in models.

Pydantic is written in Rust, making it highly performant and production-ready. It also offers far more than just basic type validation, including features like complex data structures, custom validators, and automatic type coercion.

Instead of reinventing the wheel, I strongly recommend using the existing solution, which is well-optimized, widely adopted, and thoroughly tested.

Your code example may be rewritten like this:

from pydantic import BaseModel, StrictInt, Field

class Dummy(BaseModel):
    p_1: str
    p_2: StrictInt = Field(lt=10)


valid_data = Dummy(p_1="test", p_2=1)

# Next lines will raise pydantic.ValidationError
invalid_data_1 = Dummy(p_1="test", p_2=99)
invalid_data_2 = Dummy(p_1="test", p_2=-10)
invalid_data_3 = Dummy(p_1=0, p_2=1)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744243910a4564834.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信