0

I need to use dynamic import a module from a variable.

My problem is, that importing module is in directory.

Like this:

from A.B.C import D

How can I import dynamic?

Like this...

  module = __import__('A.B.{0}'.format('C'))
  my_class = getattr(module, 'D')
  instance = my_class()

I am getting a error: AttributeError: module 'A' has no attribute 'D'

Why?

Python 3.

drothouu
  • 35
  • 1
  • 6
  • 1
    Possible duplicate of [Dynamic module import in Python](https://stackoverflow.com/questions/301134/dynamic-module-import-in-python) – Chen A. Aug 01 '18 at 10:26

2 Answers2

0

try using the import lib. The use of private functions is to the preferred way for loading modules.

module_object = importlib.import_module(module_name)

Is the location of your module part of the python path?

wat
  • 32
  • 5
0

You have to pass the fromlist argument in order to import a specific module under a package:

module = __import__('A.B.{0}'.format('C'), fromlist=('D',))
instance = D()

Please refer to __import__'s documentation for more details.

blhsing
  • 91,368
  • 6
  • 71
  • 106