14

I create a python-packages /MyLibPackage which I will import in my projects.

MyLibPackage.____init____.py includes mymodiciation.py. Furthermore the MyLibPackage Folder contains another file :base_classes.py(=external project)

mymodiciation.py imports "from base_classes import *".

Goal: I can import MyLibPackage which has all classes from base_classes (=external project). And if I have need to modifiy some classes or functions, I can overwrite this in mymodiciation.py. It works but I got a problem. For example:

I overwrite this classes in mymodiciation.py:

class Bookcollection(Bookcollection):
   new_member = "lalala"


class user(user):
   def get_books(self):
      return Bookcollection()

if I do:

from MyLibPackage import *
x = user()
books = x.get_books()

then the object Bookcollection has the property "new_member". Good! But if i will do this:

from MyLibPackage import *
x = shelf() #this class is not overwritten and used also the object "Bookcolelction"
books = x.get_books()

then the object Bookcollection has NOT the property "new_member" because he is instanced with MyLibPackage.base_classes.Bookcollection and not with my overwritten class MyLibPackage.mymodiciation.Bookcollection

How can I say: If I overwrite a class in mymodiciation then MyLibPackage has to use this although when the call cames from MyLibPackage.base_classes.shelf (get_books).

2
  • if you get tangled up in inheritance chains then maybe you ought to look at some other solutions.
    – jldupont
    Apr 5, 2012 at 11:52
  • Maybe I could try to work with hooks?!
    – bob morane
    Apr 5, 2012 at 12:27

2 Answers 2

24

What you want to do is called "monkey patching", and has little to do with Object Orientation.

Python does support it, but you have control over all your classes, you should seriously review your project to check if you will really need it.

Maybe using a framework like Zope Component Architecture, which allows you to mark classes with interfaces, and provides adapter objects so that you can cleanly use one object as having some interface it was not designed to have in first place, will be a better idea.

That said, what you are asking for is to change the class, in the other module, where it is - so that the changes are visible to all the other modules.

You do just that: change the class in the module where it belongs. In Python it can be done simply attributing your new class to the desired name, in the module of origin:

import base_classes

class Bookcollection(base_classes.Bookcollection):
   new_member = "lalala"

base_classes.Bookcollection = Bookcollection

(For things like this to work, you have to avoid "from x import *" in any project larger than single script - in this case you had 2 variables with the same name, and different meanings throughout your code:the base class, and the inherited class, for example. Python namespaces allow you to avoid that).

So, this will change the Bookcollection class in the base_class module - BUT only for code that will reference it from this point and on on your execution chain. If the "x" class in your example,is defined in the "base_classes" module, or otherwise is defined before the "MyModule" is imported, it will get a reference to the old "Bookcollection" class.

As you can see, it can quickly become a mess, and if you really choose this approach, the only way of keeping your project even usable, is to have unit tests to verify that all the classes that you want patched, are actually patched. Even the importing order of modules will make a difference, as you see. If you have tests place, they will break if you make imports in an order that breaks your monkey patching.

If you just need to add and replace things in an existing class, you can monkey patch the class itself to replace its components, instead of monkey patching the module it is in to replace the class. This way, the import order of modules won't matter much -- it will affect even existing instances of that class:

 import base_classes

 base_classes.Bookcollection.new_member = "lalala"

 def new_bookcol_method(self):
      pass

 # to replace or register a method in the other class:
 base_classes.Bookcollection.__dict__["old_bookcol_method"] = new_bookcol_method

This will give you a more consistent behaviour than trying to assign a new class (which is an object in itself) to the same name in the original module.

All in all, you should either do as @jamesj suggests in his answer, and use distinct classes, or if you need the dynamic behaviour, use a maintainable framework for that, like Zope Component Architecture. And whatever approach you take, do write unit tests.

4
  • Thank you for this. Solved a problem I had!
    – ehambright
    Dec 29, 2016 at 22:43
  • I'm doing this for unit tests, but I want to cancel it for other tests (one test changes the class used by the module, but another test needs to keep the original class). Do you know how to revert this or make the second test import the original class? @ehambright
    – Konrad
    Oct 30, 2019 at 16:23
  • Sorry if I misunderstood your answer, but when I try to do datetime.datetime.__dict__["strptime"] = new_strptime I get Error Contents: 'dictproxy' object does not support item assignment. What should my assignment have looked like in order to patch this strptime method in datetime.datetime? I'm not that familiar with Python, just trying to work around some long standing (caching?) bugs in existing standard library code. Should I have called datetime.datetime first to make sure it gets instantiated, or something similar?
    – Andreas
    May 29, 2020 at 0:18
  • This answer is from 2012 - it was written for Python 2 - in Python 3 you can't assign directly items in a class dict - instead, you assign to the attribute directly. However, datetime.datetime is written in native code (a builtin extension), and as such, one can't overwrite its methods in this way. That is: datetime.datetime.strptime = new_strptime will fail. You have to resort to subclass datetime.datetime and write the new method you want to override the older. Then, if needed, you monkey-patch the original datetime class in the module that should be using your new strptime
    – jsbueno
    May 29, 2020 at 2:21
1

Having classes with the same name is generally a bad idea as you get namespace clashes. I would recommend changing your MyLibPackage.base_classes.Bookcollection to MyLibPackage.base_classes.BaseBookcollection or similar. This should then work as expected.

2
  • But how should it works when I have the need to changes only some pieces of a baseclass? For exmaple a function. The rest of base_class.py works with his namespaces. The calls in the rest of base_classes dont know about my new derived classes
    – bob morane
    Apr 5, 2012 at 12:06
  • Ok, then rename your derived class to BookcollectionImproved or do something like from base_classes import Bookcollection as BaseBookcollection!
    – phobie
    Sep 25, 2012 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.