Pythonic way to get `package.module.Class`

For string a, the form is 'package.module.Class' , is there any simple way in Python to get a class object directly (if the module has not been imported yet)?

If not, what is the cleanest way to separate the 'package.module' part from the 'Class' , __import__() from the module, and then get the class from this?

+4
source share
2 answers
 import sys def str_to_obj(astr): ''' str_to_obj('scipy.stats.stats') returns the associated module str_to_obj('scipy.stats.stats.chisquare') returns the associated function ''' # print('processing %s'%astr) try: return globals()[astr] except KeyError: try: __import__(astr) mod=sys.modules[astr] return mod except ImportError: module,_,basename=astr.rpartition('.') if module: mod=str_to_obj(module) return getattr(mod,basename) else: raise 
+3
source

Try something like this:

 def import_obj(path): path_parts = path.split(".") obj = __import__(".".join(path_parts[:-1])) path_remainder = list(reversed(path_parts[1:])) while path_remainder: obj = getattr(obj, path_remainder.pop()) return obj 

This will work for anything that can be getattr from a module, for example. module level functions, constants, etc.

+3
source

All Articles