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.