How do I override a Python import?

后端 未结 3 1135
一个人的身影
一个人的身影 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: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"
    

    ?

提交回复
热议问题