0

i'd like to assign string to variable and then use it. Here is part of my code:

    power = input()
    if power == 1:
        mode = "CONTOUR"
    elif power == 2:
        mode = 'EDGE_ENHANCE_MORE'
    elif power == 3:
        mode = EDGE_ENHANCE
    else:
        print "Wrong option"
    try:
        img = img.filter(ImageFilter.mode)
        img.show()
    except:
        print "You should load image first"

none of mode option works

3
  • what do you mean the option "doesn't work"? Commented May 1, 2017 at 16:06
  • Probably you should put EDGE_ENHANCE between quotes for the sake of coherence. Are you getting a NameError exception? Commented May 1, 2017 at 16:09
  • when i tap 1, i won t compilator to use CONTOUR in place of mode,i get this kind of error: Traceback (most recent call last): File "./edytor.py", line 65, in <module> img = img.filter(ImageFilter.mode) AttributeError: 'module' object has no attribute 'mode' Commented May 1, 2017 at 16:10

1 Answer 1

1

I can catch at least two things: first a possible NameError at option 3 and second you are possibly eating an AttributeError exception.

A catch-all except clause is a code smell, it will mask the real cause of the error condition. Instead, try to limit the except to exceptions you are expecting or print the exception so it will hint you about the real problem.

Try this:

power = input()
if power == 1:
    mode = "CONTOUR"
elif power == 2:
    mode = 'EDGE_ENHANCE_MORE'
elif power == 3:
    mode = "EDGE_ENHANCE"
else:
    print "Wrong option"
try:
    img = img.filter(getattr(ImageFilter, mode))
except Exception as e:
    print "Ooops! Got a '{}' exception ({})".format(type(e), str(e))
else:
    img.show()

[update]

when i tap 1, i won t compilator to use CONTOUR in place of mode,i get this kind of error: Traceback (most recent call last): File "./edytor.py", line 65, in img = img.filter(ImageFilter.mode) AttributeError: 'module' object has no attribute 'mode'

Yes, as I suspected. This will try to access a attribute called 'mode' in the ImageFilter module (and since the module has no mode attribute, you get the AttributeError):

ImageFilter.mode

You don't want that. Instead, you want ImageFilter.CONTOUR. So how do you call an attribute dynamically in Python if all you have is its name stored in a variable? Something like ImageFilter[mode] work in Javascript but not in Python. Well, easy enough, in Python you must use getattr:

getattr(ImageFilter, "CONTOUR")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.