How to selectively import a module in python?

I have several different modules, and I need to import one of them depending on different situations, for example:

if check_situation() == 1: import helper_1 as helper elif check_situation() == 2: import helper_2 as helper elif ... ... else: import helper_0 as helper 

these helpers contain the same dictionaries dict01 , dict02 , dict03 ... but have different meanings that need to be called in different situations.

But this has some problems:

  • import bids are written to the top of the file, but the check_situation() function needs prerequisites here so that it is now far from the top.
  • more than 1 file needs this auxiliary module, therefore it is difficult and ugly to use this type of import.

So how to reinstall these helpers?

+7
source share
4 answers

Solve it yourself by referring to @Michael Scott Cuthbert

 # re_direct.py import this_module import that_module wanted = None # caller.py import re-direct ''' many prerequisites ''' def imp_now(case): import re_direct if case1: re_direct.wanted = re_direct.this_module elif case2: re_direct.wanted = re_direct.that_module 

then if in the caller, I call that imp_now, and then wanted to, regardless of whether you called in the calling file or another file that calls it, everyone will be redirected to this_or_that_module.

also, since I only import re_direct into a function, so you will not see this module anywhere, but only see what you want.

+1
source

You can use __import__() , it takes a string and returns this module:

 helper=__import__("helper_{0}".format(check_situation())) 

example:

 In [10]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': "))) enter 'c' or '': c #imports cmath In [11]: mod.__file__ Out[11]: '/usr/local/lib/python2.7/lib-dynload/cmath.so' In [12]: mod=__import__("{0}math".format(raw_input("enter 'c' or '': "))) enter 'c' or '': In [13]: mod.__file__ Out[13]: '/usr/local/lib/python2.7/lib-dynload/math.so' 

As @wim pointed out and from the python3.x docs on __import__() :

Import module. Since this function is intended to be used by the Python interpreter, and not for general use, it is better to use importlib.import_module() to programmatically import the module.

+4
source

Firstly, there is no strict requirement that import statements should be at the top of the file; this is more of a style guide.

Now importlib and dict can be used to replace the if / elif chain:

 import importlib d = {1: 'helper_1', 2: 'helper_2'} helper = importlib.import_module(d.get(check_situation(), 'helper_0')) 

But this is just syntactic sugar indeed, I suspect you have a big fish to fry. It sounds like you need to rethink your data structures and reverse engineer the code.

Anytime when you have variables named dict01 , dict02 , dict03 , this is a sure sign that you need to raise the level and have a container of dicts , for example. list of them. The same applies to helper module names ending in numbers.

+3
source

I agree that the approaches given in other answers are closer to the main question asked in your title, but if the overhead for importing modules is low (since it is likely that several dictionaries are imported), and there are no side effects when importing in this case you might be better off not importing them all and then choosing the correct dictionary later in the modules:

 import helper_0 import helper_1 ... helperList = [helper_0, helper_1, helper_2...] ... helper = helperList[check_situation()] 
+1
source

All Articles