flashburn flashburn - 25 days ago 9
Python Question

import only some parts of a module, but list those parts as strings

This question was marked as duplicate. However the duplicate questions deals with modules while my question is asking for how to import parts of module.

I know that I can

import
certain portions of the module by using
from mymodule import myfunction
. What if want to import several things, but I need to list them as strings. For example:

import_things = ['thing1', 'thing2', 'thing2']
from mymodule import import_things


I did ask this question, but it looks like I need to use the trick (if there is one) above for my code as well.

Any help is appreciated.

Answer
import importlib

base_module = importlib.import_module('mymodule')
imported_things = {thing: getattr(base_module, thing) for thing in import_things}

imported_things['thing1']() # Function call

If you want to be able to use the things which have been imported globally, then do:

globals().update(imported_things)
thing1() # function call

To remove the imports, you can do

del thing1

or

del globals()['thing1']

Another useful operation you can do is to reload a module

Comments