Python - Call a function in a module dynamically
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.
you need built-in getattr
:
getattr(filters, method)(**options)
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.
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.
精彩评论