Jan-30-2018, 06:42 AM
I have two base classes FirstBaseClass and SecondBaseClass and lot of theirs subclasses. Each subclass defined in the separate file, location of these files is known. I need to import and instantiate subclasses programmatically. Now I use following approach:
But problem is that I need to know class name. Is it possible to import class from file without knowing its name, assuming that only one class defined in that file?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import inspect import importlib class_name = "FirstChildClass" file_path = "/path/to/class.py" try : spec = importlib.util.spec_from_file_location(class_name, file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) for x in dir (module): obj = getattr (module, x) if inspect.isclass(obj) and ( issubclass (obj, FirstBaseClass) or issubclass (obj, SecondBaseClass)) and obj.__name__ = = class_name: return obj() except ImportError as e: print (e) |