Search code examples
pythonpython-import

python importlib.import_module into current scope


I'm following in a long line of people struggling with importlib (1, 2) (I have also read the docs).

I want to import all the elements in a list into the current scope as if I had done import my_package1; import my_package2' .... The problem is that importlib.import_module(module) returns the module rather than adding it to the scope so it can be used. I am trying to expose submodules which is why I don't want them in a variable


Solution

  • What I figured out is that you can set sys.module attributes. For published modules this takes the form

    import importlib, sys
    
    module = 'os'
    module_handle = importlib.import_module(module)    
    setattr(sys.modules[__name__], module, module_handle)
    
    os.getenv('SHELL')
    
    '/bin/bash'
    

    For local packages (the use case I'm interested in) you need to do define module_handle a bit differently by specifying the package option

    module_handle = importlib.import_module('.' + module, __name__)