2

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 ?

pylover
  • 7,670
  • 8
  • 51
  • 73
gargi258
  • 829
  • 1
  • 10
  • 16

1 Answers1

2

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__

pylover
  • 7,670
  • 8
  • 51
  • 73