Biplov Dahal Biplov Dahal - 18 days ago 4x
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

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

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

Also I tried this

user_input = 'GaussianBlur'
def ImageFilterUsingPil():
im ='hotdog.jpg')

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


You are looking to use getattr here.

call = getattr(ImageFilter, user_input)

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')()

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:
    # do fail logic here