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:
check_situation()
function here needs prerequisites so that it's now far from top.So, how to re-arrange these helpers?
You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.
General imports, like import math , make all functionality from the math package available to you. However, if you decide to only use a specific part of a package, you can always make your import more selective: from math import pi.
append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.
Python conditional import comes into use while importing modules. In python, modules are pieces of code containing a set of functions that can be imported into other code. Modules help in managing code by supporting readability.
Firstly, there is no strict requirement that import statements need to be at the top of a file, it is more a style guide thing.
Now, importlib
and a dict
can be used to replace your if
/elif
chain:
import importlib
d = {1: 'helper_1', 2: 'helper_2'}
helper = importlib.import_module(d.get(check_situation(), 'helper_0'))
But it's just syntactic sugar really, I suspect you have bigger fish to fry. It sounds like you need to reconsider your data structures, and redesign code.
Anytime you have variables named like dict01
, dict02
, dict03
it is a sure sign that you need to gear up a level, and have some container of dicts
e.g. a list of them. Same goes for your 'helper' module names ending with digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With