Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically import a method in a file, from a string

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.

like image 662
lprsd Avatar asked Jan 09 '12 14:01

lprsd


People also ask

What is __ import __ in Python?

__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.

What does Importlib Import_module do?

The import_module() function acts as a simplifying wrapper around importlib. __import__() . This means all semantics of the function are derived from importlib.

What is lazy import Python?

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.


2 Answers

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() 
like image 54
frm Avatar answered Sep 28 '22 05:09

frm


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.

like image 31
Sven Marnach Avatar answered Sep 28 '22 04:09

Sven Marnach