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

<p>I want to be able to replace (<em>ImagerFilter.user_input</em>) and call that filter.(Line 3)</p>

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

<p>Also I tried this</p>

<pre><code>user_input = 'GaussianBlur'
def ImageFilterUsingPil():
    im = Image.open('hotdog.jpg')
    im.filter(ImageFilter.user_input) 
    im.save('hotdog.png')
</code></pre>

<p>it threw me <code>AttributeError: 'module' object has no attribute 'user_input'</code></p>

<p>You are looking to use <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow">getattr</a> here. </p>

<pre><code>call = getattr(ImageFilter, user_input)
call()
</code></pre>

<p>More explicit to your code, you can do this: </p>

<pre><code>im.filter(getattr(ImageFilter, user_input)()) 
</code></pre>

<p>Simple example: </p>

<pre><code>&gt;&gt;&gt; class Foo:
...     @classmethod
...     def bar(cls):
...         print('hello')
...
&gt;&gt;&gt; getattr(Foo, 'bar')()
hello
</code></pre>

<p>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 <code>try/except</code>. </p>

<pre><code>&gt;&gt;&gt; try:
...     getattr(Foo, 'bar')()
... except AttributeError:
...     # do exception handling here
</code></pre>

<p>You could also assign a default as <code>None</code> (Personally I would rather (<a href="http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python">EAFP</a>) and then check to see if it is not <code>None</code> before calling it: </p>

<pre><code>call = getattr(ImageFilter, user_input, None)
if call:
    call()
else:
    # do fail logic here
</code></pre>

python function