2

I want to override a module of an existing Python application. The application is structured in modules and submodules and I have registered an extension. Within the extension I want to provide a module (new_module.py) which overrides the original module (module.py). So whenever another module imports it, my version is used.

/application
    __init__.py
    folder_a
    folder_b
       __init__.py
       folder_b_a
           __init__.py
           module.py
/extension
    __init__.py
    new_module.py

I guess this can be achieved by setting it in the sys module, like this:

import extension.new_module
sys.modules["application.folder_b.folder_b_a.module"] = extension.new_module

But I am not sure where to put those lines. I tried it in all of the init files, but it does not work. Or is there another way?

linsenfips
  • 698
  • 6
  • 25
  • have a look at http://stackoverflow.com/questions/3012473/how-do-i-override-a-python-import maybe this is what you are looking for. – WWhisperer Apr 07 '15 at 12:23
  • Yes, that's where I got the sys.module idea from. But they are overriding it just in one file. – linsenfips Apr 07 '15 at 12:32

1 Answers1

0

Documented here: https://docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP

Force python to load your extension via the environment variable, and in that extension import sys and mess about with sys.modules.

Dima Tisnek
  • 10,388
  • 4
  • 61
  • 113