Skip to content Skip to sidebar Skip to footer

Python 3 Automatic Conditional Import?

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 pyth

Solution 1:

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))

Solution 2:

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.

Solution 3:

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

Post a Comment for "Python 3 Automatic Conditional Import?"