I have a set of data-struct like classes that correspond to the JSON messages being exchanged between services in an overall architecture. By struct like, I mean these classes just have fields -- no member functions -- and are implemented using pydantic
since this makes for easy development using fastapi
. There is currently a design decision to keep these classes "pure" in the sense that they only define data members (think C-struct). These classes are nested in the sense that some of the classes have members that are (collections of) other classes defined here.
In order to support good design within a service, I believe it is desirable to define member functions for operating on/with these data classes. For example, consider the case below:
class Disk(pydantic.BaseModel):
x: float
y: float
r: float
class Scene(pydantic.BaseModel):
disks: list[Disk]
name: str
To me, it is natural for there to be a Disk.hit(self, x:float, y:float) -> bool
that returns True
if the arguments define a point that is within the radius (r
) of the center of the disk. Similarly, a function like Scene.hits(self, x, y) -> int
that returns the number of disks that lie under a given point makes sense.
Is this a valid use case for using monkey-patching in order to add these member functions after the fact? Are there risks/drawbacks other than the function-name collision one (which should be manageable by constraining the monkey patching to only occur within one specific package)?