Python: Dynamically import modules and objects
<p>I want import dynamically some class through variable like:</p>

<pre><code>classes = ['AaaBc', 'AccsAs', 'Asswwqq']
for class in classes:
    from file.models import class
</code></pre>

<p>How can I do it ?</p>

<p>use <code>__import__</code></p>

<pre><code>spam = __import__('spam', globals(), locals(), [], 0)
</code></pre>

<p>The statement import spam.ham results in this call:</p>

<pre><code>spam = __import__('spam.ham', globals(), locals(), [], 0)
</code></pre>

<p>Note how <strong>import</strong>() returns the toplevel module here because this is the object that is bound to a name by the import statement.</p>

<p>On the other hand, the statement from spam.ham import eggs, sausage as saus results in</p>

<pre><code>_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
</code></pre>

<p>see: <a href="https://docs.python.org/3/library/functions.html#__import__" rel="nofollow">https://docs.python.org/3/library/functions.html#<strong>import</strong></a></p>

python python-import