rochacbruno-archive / import_string

Imports an object based on a string import_string('package.module:function_name')() - Based on werkzeug.utils

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sharing some experience

felipevolpone opened this issue · comments

Hi @rochacbruno, nice work exporting this code to a new library, it's really usefull :)

I've done done this kind of import in some projects, but using this approach:

import importlib
foopath = 'src.apis.foo.Foo'

module_name = '.'.join(foopath.split('.')[:-1]) # to get src.apis.foo
foo_module = importlib.import_module(module_name)
clazz_name = foopath.split('.')[-1] # to get Foo
Foo = getattr(module_name, clazz_name)
print Foo()

It's almost the same thing, but using importlib instead of import directly. Actually, importlib uses the import function as well. Anyway, just creating this issue to share some alternatives to the same goal.

Thank you!