3

I'm trying to import a module using __import__(). I need to use __import__ becuase I don't know which module I'll need before runtime.

Let's say the module I'll need is MyClass. The file tree is api/apps/myapp/my_class.py, and the class i have in my_class.py is MyClass. Now, to access the methods of MyClass what I'm doing is this:

my_class_module =  __import__('api.apps.myapp.my_class')
my_class= my_class_module.MyClass()

But I'm getting this error: 'module' object has no attribute 'MyClass'

Any ideas?

MeLight
  • 5,454
  • 4
  • 43
  • 67
  • possible duplicate http://stackoverflow.com/questions/2724260/why-does-pythons-import-require-fromlist – Pradeeshnarayan Oct 07 '13 at 09:21
  • It seems to be a duplicate, however here the question is practical: "how do I" when in http://stackoverflow.com/questions/2724260/why-does-pythons-import-require-fromlist it is a "how does it works" question. Same for the answers. – Juh_ Oct 07 '13 at 09:28
  • In case the *possible duplicate* is not asserted, I'll add a link to this details explanation in my answer. – Juh_ Oct 07 '13 at 09:31

1 Answers1

3

By default, __import__ return a reference to the first module. In your example, it is api. The solution is to use the fromlist parameter:

my_class_module =  __import__('api.apps.myapp.my_class', fromlist=[''])

From the __import__ documentation:

[...] When importing a module from a package, note that ___import___('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. [...]

For details on the reason it does so, see Why does Python's __import__ require fromlist?

Community
  • 1
  • 1
Juh_
  • 14,628
  • 8
  • 59
  • 92