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.
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.
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.
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.
you need built-in getattr
:
getattr(filters, method)(**options)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With