Search code examples
pythonvalidationdesign-patternsmodelpydantic

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


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.


Solution

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