I have a string, say: abc.def.ghi.jkl.myfile.mymethod
. How do I dynamically import mymethod
?
Here is how I went about it:
def get_method_from_file(full_path): if len(full_path) == 1: return map(__import__,[full_path[0]])[0] return getattr(get_method_from_file(full_path[:-1]),full_path[-1]) if __name__=='__main__': print get_method_from_file('abc.def.ghi.jkl.myfile.mymethod'.split('.'))
I am wondering if the importing individual modules is required at all.
Edit: I am using Python version 2.6.5.
__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.
The import_module() function acts as a simplifying wrapper around importlib. __import__() . This means all semantics of the function are derived from importlib.
Lazy import is a very useful feature of the Pyforest library as this feature automatically imports the library for us, if we don't use the library it won't be added. This feature is very useful to those who don't want to write the import statements again and again in their code.
From Python 2.7 you can use the importlib.import_module() function. You can import a module and access an object defined within it with the following code:
from importlib import import_module p, m = name.rsplit('.', 1) mod = import_module(p) met = getattr(mod, m) met()
You don't need to import the individual modules. It is enough to import the module you want to import a name from and provide the fromlist
argument:
def import_from(module, name): module = __import__(module, fromlist=[name]) return getattr(module, name)
For your example abc.def.ghi.jkl.myfile.mymethod
, call this function as
import_from("abc.def.ghi.jkl.myfile", "mymethod")
(Note that module-level functions are called functions in Python, not methods.)
For such a simple task, there is no advantage in using the importlib
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With