tags:

views:

72

answers:

3

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.

+4  A: 

you need built-in getattr:

getattr(filters, method)(**options)
SilentGhost
Awesome, thank you!
Chris Forrette
+7  A: 

To avoid the problem, you could pass the function directly, instead of "by name":

def process_images(method=filters.scale, options):
    method(**options)

If you have a special reason to use a string instead, you can use getattr as suggested by SilentGhost.

sth
Perfect -- thanks!
Chris Forrette
A: 
import filters

def process_images(function=filters.scale, options):
    function(**options)

This can then be called like, for example:

process_images(filters.rotate, **rotate_options)

Note that having a default function arg doesn't seem like a good idea -- it's not intuitively obvious why filters.scale is the default out of several possible image-processing operations.

John Machin