Biplov Dahal Biplov Dahal - 2 months ago 14
Python Question

Call module.Functionname from user input

I'm trying to call module(.)functionname from a image lirary upon user input.
For instance a user types in
"GaussianBlurr"

I want to be able to replace (ImagerFilter.user_input) and call that filter.(Line 3)

def ImageFilterUsingPil():
im = Image.open('hotdog.jpg')
im.filter(ImageFilter.GaussianBlur) # instead im.filter(ImageFilter.user_input)
im.save('hotdog.png')


Also I tried this

user_input = 'GaussianBlur'
def ImageFilterUsingPil():
im = Image.open('hotdog.jpg')
im.filter(ImageFilter.user_input)
im.save('hotdog.png')


it threw me
AttributeError: 'module' object has no attribute 'user_input'

Answer

You are looking to use getattr here.

call = getattr(ImageFilter, user_input)
call()

More explicit to your code, you can do this:

im.filter(getattr(ImageFilter, user_input)()) 

Simple example:

>>> class Foo:
...     @classmethod
...     def bar(cls):
...         print('hello')
...
>>> getattr(Foo, 'bar')()
hello

However, you might want to make sure you handle exceptions for when you send something invalid. So, you should probably wrap your attempt to call the method with a try/except.

>>> try:
...     getattr(Foo, 'bar')()
... except AttributeError:
...     # do exception handling here

You could also assign a default as None (Personally I would rather (EAFP) and then check to see if it is not None before calling it:

call = getattr(ImageFilter, user_input, None)
if call:
    call()
else:
    # do fail logic here
Comments