0
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!

3
  • this can be duplicate for stackoverflow.com/questions/67631/… Commented Sep 20, 2013 at 21:45
  • any way for import a package (not module) from path string and then, import the module.Class for them? Commented Sep 20, 2013 at 22:14
  • package and module are imported same way. class is module attribute, method is class atribute. Use getattr for obtaining object's attribute Commented Sep 20, 2013 at 22:17

1 Answer 1

1

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)()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.