-1

Given dot-notation of a python class, how would I import it if it's given as a string?

For example:

>>> from ingest.models import ItemInstance
>>> ItemInstance
<class 'ingest.models.ItemInstance'>

Given the string, 'ingest.models.ItemInstance', how would I import that?


Note: the above referenced duplicated is primarily about importing a module. Here I'm looking to specifically import a class. For example:

s = "ingest.models.ItemInstance"
cls = s.split('.')[-1] # works with the given path, but not always
module = '.'.join(s.split('.')[:-1])
getattr(importlib.import_module(module), cls)

The answer provided below addresses this accurately.

user12282936
  • 167
  • 2
  • 7

1 Answers1

2

In Python 2.7 and Python 3.1 or later, you can use importlib:

import importlib

i = importlib.import_module("module_name")

If you want to access the class, you can use getattr:

import importlib
module = importlib.import_module("module_name")
class_ = getattr(module, class_name)
instance = class_()
Mert Köklü
  • 2,183
  • 2
  • 16
  • 20