To avoid having to manipulate sys.path
and to keep all the extra modules you import from cluttering up sys.modules
, I'd suggest using execfile()
for this. Something like this (untested code):
import os.path
def load_and_call(package_path, module_class, method_name):
module_name, class_name = module_class.split(".")
module_globals = {}
execfile(os.path.join(package_path, module_name + ".py"), module_globals)
return getattr(module_globals[class_name](), method_name, lambda: None)()
You could add some code to cache the parsed objects using a dictionary, if a file will be used more than once (again, untested):
def load_and_call(package_path, module_class, method_name, _module_cache={}):
module_name, class_name = module_class.split(".")
py_path = os.path.join(package_path, module_name + ".py")
module_globals = _module_cache.setdefault(py_path, {})
if not module_globals:
execfile(py_path, module_globals)
return getattr(module_globals[class_name](), method_name, lambda: None)()