Q:

django - import different module when variable change

I wanna import different module as the variable a changed.
#views.py
path = os.path.normpath(os.path.join(here, 'module/%s' % a))
sys.path.append(path)
from foo import bar
sys.path.remove(path)

And my folder show as below:
djangoapp---module----a----index.py & __init.py
              |-------b----index.py & __init.py
              views.py

I doing this way is worked, but is there any other way to switch the module when the variable a changed?
My friend tell me it's better not to modify the content of the sys.path during the process.

A:

Instad of fiddling with the sys.path, you can just import from a different location, like:
module_name = 'a.foo'
module = __import__(module_name, globals(), locals(), ['*'])

See more in the docs to __import__.
Maybe importlib.import_module will be even a better choice.

