Skip to content Skip to sidebar Skip to footer

Is It A Bad Practice To Override A Method Of A Class In An Instance?

Let’s say that I write a metaclass M and a user writes an instance A of my metaclass which overrides a method g: >>> class M(type): ... def f(self): return self.g()

Solution 1:

The only valid answer here is the same as the old chestnut response the doctor gives when you ask what to do about the pain you feel when you jab yourself in the eye repeatedly: If it hurts, stop doing that. Your eye was not designed to have a finger jabbed in it.

So, yes, it is bad practice to add a method to an instance or a class when it breaks the expectations of the existing code that calls it.

Note that this has really nothing to do with the specifics of your examples. Any existing code can be broken this way, by replacing or shadowing something else with an implementation that doesn't fit the existing expectations.

Your examples can be trivially fixed; to replace the M.g method on a class, use a class method. To replace A.g on the instance, use a function that doesn't expect self. Both would fit the expectations of the existing code: that calling g does not require additional arguments.

Python is highly dynamic, and that gives you loads and loads of freedom, including the freedom to poke yourself in the proverbial eye. Try not to do that last thing or anything else that could hurt your code, and you should be fine.

Solution 2:

The rare cases in which monkey-patching has to be used as a last resort tend to be cases where you don't have access to the source code to implement a proper solution, or where you're somehow unable to define a subclass of the class you're hoping to fix or extend.

It's a bad practice in most other cases and often a final resort in a codebase that has become burdened with too many bad design decisions, when it's not trying to fix a third party solution for which you don't have the code.

Post a Comment for "Is It A Bad Practice To Override A Method Of A Class In An Instance?"