Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is calling module and function by string handled in python?

Tags:

python

Calling a function of a module from a string with the function's name in Python shows us how to call a function by using getattr("bar")(), but this assumes that we have the module foo imported already.

How would would we then go about calling for the execution of "foo.bar" assuming that we probably also have to perform the import of foo (or from bar import foo)?

like image 233
Xarses Avatar asked Jul 10 '11 19:07

Xarses


People also ask

How do you call a function from a module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How do you call a function object in Python?

Use parentheses to call a function in Python To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function).


2 Answers

Use the __import__(....) function:

http://docs.python.org/library/functions.html#import

(David almost had it, but I think his example is more appropriate for what to do if you want to redefine the normal import process - to e.g. load from a zip file)

like image 115
user488551 Avatar answered Sep 29 '22 20:09

user488551


You can use find_module and load_module from the imp module to load a module whose name and/or location is determined at execution time.

The example at the end of the documentation topic explains how:

import imp
import sys

def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

    # If any of the following calls raises an exception,
    # there's a problem we can't handle -- let the caller handle it.

    fp, pathname, description = imp.find_module(name)

    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()
like image 43
David Heffernan Avatar answered Sep 29 '22 21:09

David Heffernan