import_function_resized
Rewriting my application on Django,
I needed to import classes without knowing their names first
(just reading them out of a directory).
Obviously something like this:

1
2
module_name = 'module_foo'
import module_name

will just try to import "module_name", and doesn't work the way it's suppose to.
So, what did I do? I solved it by using the __import__ function!
__import__ lets you import modules with parameters given, for instance:
1
2
3
4
urllib = __import__(name='urllib') # import urllib</p>
<p>#lets say we want &quot;from lxml import etree as tree_module&quot;
lxml_module = __import__(name='lxml', fromlist=['etree'])
tree_module = lxml_module.etree

After implementing this, I found out that there's a better, more convenient wrapper for the __import__ function,
the code for which would look like this:

1
2
import importlib
tree_module = importlib.import_module('lxml.etree') #import lxml.etree as tree_module

Both are valid though (because importlib is only a wrapper)