How to selectively import module in python?
Question: 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 same dictionaries `dict01`, `dict02`, `dict03`...but
have different values to be called in different situations.

But this has some problems:

  1. import sentences are all written in the top of a file, but `check_situation()` function here needs prerequisites so that it's now far from top.
  2. more than 1 file needs this helper module, so it's hard and ugly to use this kind of import.

So, how to re-arrange these helpers?


Answer: You can use `__import__()`, it accepts a string and returns that 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 pointed out by @wim and from python3.x docs on `__import__()`:

> Import a module. Because this function is meant for use by the Python
> interpreter and not for general use it is better to use
> `importlib.import_module()` to programmatically import a module.

