Python: How can I override one module in a package with a modified version that lives outside the pa

Posted by zlovelady on Stack Overflow See other posts from Stack Overflow or by zlovelady
Published on 2010-05-22T05:19:59Z Indexed on 2010/05/22 5:30 UTC
Read the original article Hit count: 206

Filed under:
|

I would like to update one module in a python package with my own version of the module, with the following conditions:

  • I want my updated module to live outside of the original package (either because I don't have access to the package source, or because I want to keep my local modifications in a separate repo, etc).
  • I want import statements that refer to original package/module to resolve to my local module

Here's an example of what I'd like to do using specifics from django, because that's where this problem has arisen for me:

Say this is my project structure

django/
  ... the original, unadulterated django package ...
local_django/
  conf/
    settings.py
myproject/
  __init__.py
  myapp/
    myfile.py

And then in myfile.py

# These imports should fetch modules from the original django package
from django import models
from django.core.urlresolvers import reverse

# I would like this following import statement to grab a custom version of settings 
# that I define in local_django/conf/settings.py 
from django.conf import settings

def foo():
  return settings.some_setting

Can I do some magic with the __import__ statement in myproject/__init__.py to accomplish this? Is there a more "pythonic" way to achieve this?

© Stack Overflow or respective owner

Related posts about python

Related posts about django