Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to selectively import 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 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?

like image 299
ThunderEX Avatar asked Mar 13 '13 02:03

ThunderEX


People also ask

How do I import a specific module in Python?

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.

What is selective import?

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.

Can you manually import a module in Python?

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.

Can import be conditional in Python?

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.


1 Answers

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.

like image 188
wim Avatar answered Oct 22 '22 01:10

wim