Swapping superclass from a module

Terry Reedy tjreedy at udel.edu
Sun May 17 08:08:01 CEST 2009


Steven D'Aprano wrote:
> On Sat, 16 May 2009 09:55:39 -0700, Emanuele D'Arrigo wrote:
> 
>> Hi everybody,
>>
>> let's assume I have a module with loads of classes inheriting from one
>> class, from the same module, i.e.:
> [...]
>> Now, let's also assume that myFile.py cannot be changed or it's
>> impractical to do so. Is there a way to replace the SuperClass at
>> runtime, so that when I instantiate one of the subclasses NewSuperClass
>> is used instead of the original SuperClass provided by the first module
>> module?
> 
> That's called "monkey patching" or "duck punching".
> 
> http://en.wikipedia.org/wiki/Monkey_patch
> 
> http://wiki.zope.org/zope2/MonkeyPatch
> 
> http://everything2.com/title/monkey%2520patch

If the names of superclasses is resolved when classes are instantiated, 
the patching is easy.  If, as I would suspect, the names are resolved 
when the classes are created, before the module becomes available to the 
importing code, then much more careful and extensive patching would be 
required, if it is even possible.  (Objects in tuples cannot be 
replaced, and some attributes are not writable.)

tjr




More information about the Python-list mailing list