Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Call a function in a module dynamically

Tags:

python

I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have filters.py:

def scale(image, width, height):
    pass

And then in another script I have something like:

import filters

def process_images(method='scale', options):
    filters[method](**options)

... but that doesn't work obviously. If someone could fill me in on the proper way to do this, or let me know if there is a better way to pass around functions as parameters that would be awesome.

like image 529
Chris Forrette Avatar asked Jul 06 '10 22:07

Chris Forrette


People also ask

How do you call a function dynamically in Python?

To do this in Python you have to access the global namespace. Python makes you do this explicitly where PHP is implicit. In this example we use the globals() function to access the global namespace. globals() returns a dictionary that includes area as a key and the value is a reference to the area() function.

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 create a dynamic function in Python?

Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.


1 Answers

you need built-in getattr:

getattr(filters, method)(**options)
like image 127
SilentGhost Avatar answered Nov 02 '22 07:11

SilentGhost