Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to include non-validating methods in a pydantic model?

Tags:

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.

like image 933
ccred Avatar asked Feb 03 '20 21:02

ccred


People also ask

Can Pydantic models have methods?

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 ...

Why should I use Pydantic?

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.

What are Pydantic models?

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.

What is Pydantic in Python?

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.”


1 Answers

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.

like image 175
SColvin Avatar answered Sep 28 '22 08:09

SColvin