How do I override a Python import? How do I override a Python import? python python

How do I override a Python import?


Does this answer your question? The second import does the trick.

Mod_1.py

def test_function():    print "Test Function -- Mod 1"

Mod_2.py

def test_function():    print "Test Function -- Mod 2"

Test.py

#!/usr/bin/pythonimport sysimport Mod_1Mod_1.test_function()del sys.modules['Mod_1']sys.modules['Mod_1'] = __import__('Mod_2')import Mod_1Mod_1.test_function()


To define a different import behavior or to totally subvert the import process you will need to write import hooks. See PEP 302.

For example,

import sysclass MyImporter(object):    def find_module(self, module_name, package_path):        # Return a loader        return self    def load_module(self, module_name):        # Return a module        return selfsys.meta_path.append(MyImporter())import now_you_can_import_any_nameprint now_you_can_import_any_name

It outputs:

<__main__.MyImporter object at 0x009F85F0>

So basically it returns a new module (which can be any object), in this case itself. You may use it to alter the import behavior by returning processe_xxx on import of xxx.

IMO: Python doesn't need a preprocessor. Whatever you are accomplishing can be accomplished in Python itself due to it very dynamic nature, for example, taking the case of the debug example, what is wrong with having at top of file

debug = 1

and later

if debug:   print "wow"

?


In Python 2 there is the imputil module that seems to provide the functionality you are looking for, but has been removed in python 3. It's not very well documented but contains an example section that shows how you can replace the standard import functions.

For Python 3 there is the importlib module (introduced in Python 3.1) that contains functions and classes to modify the import functionality in all kinds of ways. It should be suitable to hook your preprocessor into the import system.