Import class from module dynamically

 GhostKU  picture GhostKU · Jan 16, 2017 · Viewed 17.3k times · Source

I have class called 'my_class' placed in 'my_module'. And I need to import this class. I tried to do it like this:

import importlib
result = importlib.import_module('my_module.my_class')

but it says:

ImportError: No module named 'my_module.my_class'; 'my_module' is not a package

So. As I can see it works only for modules, but can't handle classes. How can I import a class from a module?

Answer

Dimitris Fasarakis Hilliard picture Dimitris Fasarakis Hilliard · Jan 16, 2017

It is expecting my_module to be a package containing a module named 'my_class'. If you need to import a class, or an attribute in general, dynamically, just use getattr after you import the module:

cls = getattr(import_module('my_module'), 'my_class')

Also, yes, it does only work with modules. Remember importlib.import_module is a wrapper of the internal importlib.__import__ function. It doesn't offer the same amount of functionality as the full import statement which, coupled with from, performs an attribute look-up on the imported module.