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 ?

2
  • What would be the point? What could you do with this that you couldn't do with just import file? Commented Oct 18, 2016 at 7:58
  • 1
    Possible duplicate of Dynamic module import in Python Commented Oct 18, 2016 at 7:58

1 Answer 1

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__

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.