How do I override a Python import?

后端 未结 3 1123
一个人的身影
一个人的身影 2020-12-01 01:58

I\'m working on pypreprocessor which is a preprocessor that takes c-style directives and I\'ve been able to make it work like a traditional preprocessor (it\'s self-consumin

相关标签:
3条回答
  • 2020-12-01 02:28

    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.

    0 讨论(0)
  • 2020-12-01 02:36

    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/python
    
    import sys
    
    import Mod_1
    
    Mod_1.test_function()
    
    del sys.modules['Mod_1']
    
    sys.modules['Mod_1'] = __import__('Mod_2')
    
    import Mod_1
    
    Mod_1.test_function()
    
    0 讨论(0)
  • 2020-12-01 02:39

    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 sys
    
    class 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 self
    
    sys.meta_path.append(MyImporter())
    
    import now_you_can_import_any_name
    print 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"
    

    ?

    0 讨论(0)
提交回复
热议问题