0

Is there any nice way to import different modules based on some variable value? My example:

I have a folder with different modules:

  • module_a.py
  • module_b.py

And in some other python file i want to import either module_a or module_b based on some config value:

if configVal == 'a':
    import module_a
elif configVal == 'b':
    import module_b

Is there some way to avoid using if-elifs? So somehow automatically?

like:

@conditionalImport(configVal)
import module_

Or something clever?

waszil
  • 390
  • 2
  • 5
  • 15
  • 1
    You can call `importlib.import_module()` programatically to automate this type of task if you are worried about this due to a big number of modules. For 2 it will be more code that what you would avoid. – Adirio Mar 03 '17 at 10:49
  • 1
    Note that it is perfectly normal to use `if` to decide which module to import. Take a look at the official [`os` module](https://github.com/python/cpython/blob/3.6/Lib/os.py) source code. – farsil Mar 03 '17 at 10:51

3 Answers3

3

You can use the __import__ builtin to be able to state the module name as a string.

In that way you can perform normal string operations on the module name:

module = __import__("module_{}".format(configVal))
jsbueno
  • 99,910
  • 10
  • 151
  • 209
1

As a matter of fact,we often use if else or try catch statement to write Python2/3 compatible code or avoid import errors.This is very common.

if sys.version_info[0] > 2:
    xrange = range

Or use try catch to raise exception.After modules that have been renamed, you can just import them as the new name.

try:
    import mod
except ImportError:
    import somemodule as mod

But it's bad practice to use an external script to make your script work.It is unusual to depend on external script to import modules in Python.

McGrady
  • 10,869
  • 13
  • 47
  • 69
0

It's normal to use if/try,except for import

for example

import sys
if sys.version_info > (2, 7):
    import simplejson as json
else:
    import json
Stanislav Filin
  • 124
  • 1
  • 1
  • 7