0

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'

1 Answers1

0

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
Community
  • 1
  • 1
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • Would my syntax be like this? im.filter(getattr(ImageFilter.user_input)) – Biplov Dahal Oct 03 '16 at 21:48
  • @BiplovDahal Almost. You have to actually call it. `im.filter(getattr(ImageFilter.user_input)())` – idjaw Oct 03 '16 at 21:49
  • @BiplovDahal Woops, I had a type. Do you not put command in ImageFilter,user_input instead of ImageFilter.user_input? – Biplov Dahal Oct 03 '16 at 21:57
  • I don't understand what you are asking. My answer is giving you exactly what to do. Does it not work? – idjaw Oct 03 '16 at 21:58
  • @BiplovDahal if this solution helped you, please consider marking it as accepted in order to help other readers know this solved your problem. – idjaw Oct 03 '16 at 22:26