54

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.

Paolo
  • 20,112
  • 21
  • 72
  • 113
ccred
  • 543
  • 4
  • 5
  • 2
    This is a great question. I have many use cases where I need to add some light functionality e.g. a method to construct the object from other data structures as well as validate it. Make a lot of sense to do in one class. – John Curry Feb 11 '23 at 13:57

1 Answers1

55

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.

SColvin
  • 11,584
  • 6
  • 57
  • 71
  • 7
    Thank you. I really appreciate pydantic's excellent documentation. Keep up the good work. – ccred Feb 04 '20 at 00:09