fj123x
fj123x

Reputation: 7492

python, instance dynamic module.class from given path package and call dynamic method

package_path = '/home/foo/bar/'
module_class = 'hello.World'
method = 'something'

first, i want to import the hello module what it is inside of the package_path (/home/foo/bar/)

then, i must instantiate the class World at this module

and finally i should run the something() method on the new world_instance_object

any idea for do that?

Thank you so much!

Upvotes: 0

Views: 147

Answers (1)

kindall
kindall

Reputation: 184161

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)()

Upvotes: 1

Related Questions