Use string to specify `from my_package import my_class as my_custom_name`

Viewed 40

I'd like to make the following line dynamic :

from my_package import my_class as my_custom_name

I know how to dynamically import modules via string

import importlib
module_name = "my_package"
my_module = importlib.import_module(module_name)

as suggested here. However it still doesn't let me specify the class I want to import (my_class) and the alias I want to assign to the class name (my_custom_name). I'm using python 3.6

1 Answers

Two steps. Number one, you can reference a module directly using importlib:

importlib.import_module('my_package.my_module') # You can use '.'.join((my_package, my_module))

Your class will be contained in the module itself as an attribute, as in any import. As such, just use

my_custom_name = importlib.import_module('my_package.my_module').__dict__['my_class']

or even better

my_custom_name  = getattr(importlib.import_module('my_package.my_module'), 'my_class')
Related