I want import dynamically some class through variable like:
classes = ['AaaBc', 'AccsAs', 'Asswwqq']
for class in classes:
from file.models import class
How can I do it ?
1 Answer 1
Use __import__
spam = __import__('spam', globals(), locals(), [], 0)
The statement import spam.ham results in this call:
spam = __import__('spam.ham', globals(), locals(), [], 0)
Note how __import__() returns the top-level module here because this is the object that is bound to a name by the import statement.
On the other hand, the statement from spam.ham import eggs, sausage as saus results in:
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
see: https://docs.python.org/3/library/functions.html#__import__
answered Oct 18, 2016 at 7:58
pylover
8,1918 gold badges53 silver badges73 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
import file?