13

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.

3 Answers 3

28

you need built-in getattr:

getattr(filters, method)(**options)
Sign up to request clarification or add additional context in comments.

1 Comment

this should be the best answer
9

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.