I'm using pydantic 1.3 to validate models for an API I am writing.
Is it common/good practice to include arbitrary methods in a class that inherits from pydantic.BaseModel?
I need some helper methods associated with the objects and I am trying to decide whether I need a "handler" class. These models are being converted to json and sent to a restful service that I am also writing.
My model looks like this:
class Foo(pydantic.BaseModel): name: str bar: int baz: int
Is it poor practice to do something like:
class Foo(pydantic.BaseModel): name: str bar: int baz: int def add_one(self): self.bar += 1
It makes some sense to me, but I can't find an example of anyone doing this.
Thank you in advance.
pydantic also provides the construct() method which allows models to be created without validation this can be useful when data has already been validated or comes from a trusted source and you want to create a model as efficiently as possible ( construct() is generally around 30x faster than creating a model with full ...
pydantic allows custom data types to be defined or you can extend validation with methods on a model decorated with the validator decorator. As well as BaseModel , pydantic provides a dataclass decorator which creates (almost) vanilla Python dataclasses with input data parsing and validation.
Pydantic models. Pydantic is a useful library for data parsing and validation. It coerces input types to the declared type (using type hints), accumulates all the errors using ValidationError & it's also well documented making it easily discoverable.
Based on the official documentation, Pydantic is. “… primarily a parsing library, not a validation library. Validation is a means to an end: building a model which conforms to the types and constraints provided. In other words, pydantic guarantees the types and constraints of the output model, not the input data.”
Yes, it's fine. We should probably document it.
The only problem comes when you have a field name which conflicts with the method, but that's not a problem if you know what your data looks like. Also, it's possible to over object orient your code, but you're a long way from that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With