Why does Python not implement the elif statement on try statement?

吃可爱长大的小学妹 提交于 2020-01-01 04:19:14

问题


So let's make a quick example.

my_list = [
    {"name": "toto", "value": 3},
    {"name": "foo", "value": 42},
    {"name": "bar", "value": 56}
]

def foo(name):
    try:
        value = next(e["value"] for e in my_list if e["name"] == name)
    except StopIteration:
        print "Uuuh not found."
    else:
        if value % 2:
            print "Odd !"
        else:
            print "Even !"

As you can see, the above code works :

>>> foo("toto")
Odd !
>>> foo("foo")
Even !
>>> foo("kappa")
Uuuh not found.

I was just wondering if there is a particular reason about why we can't use the elif statement with the try statement like this :

try:
    value = next(e["value"] for e in my_list if e["name"] == name)
except StopIteration:
    print "Uuuh not found."
elif value % 2:
    print "Odd !"
else:
    print "Even !"

Of course, this would not work because as it is defined in the try statement documentation, the elif statement is not defined. But why ? Is there a particular reason (like bound / unbound variable) ? Is there any sources about this ?

(Side note: no elif-statement tag ?)


回答1:


If you are asking why then that is a question for the python devs, the syntax is clearly defined in the docs you linked to.

Apart from that what you are trying to do can obviously all be done inside the try/except. If you use an else it belongs to the try the same as when you use an else with a for loop, I think it makes perfect sense to only use else and not allow elif, elif's are there to behave like switch/case statements in other languages.

From an old thread on gossamer-threads Why no 'elif' in try/except? :

Because it makes no sense?

The except clauses are for handling exceptions, the else clause is for handling the case when everything worked fine.

Mixing the two makes no sense. In an except clause, there is no result to test; in an else clause, there is. Is the elif supposed to execute when there are exceptions, or when there aren't? If it's simply an extension to the else clause, then I suppose it doesn't harm anything, but it adds complexity to the language definition. At this point in my life, I tend to agree with Einstein - make everything as simple as possible, but no simpler. The last place (or at least one of the many last places) I want additional complexity is in exception handling.

You always need at least one if to use an elif, it is simply invalid syntax without. The only thing that could end up not being defined is value, you should move the logic inside the try/except using if/else:

try:
    value = next(e["value"] for e in my_list if e["name"] == name)
    if value % 2:
        print("Odd !")
    else:
        print("Even !")
except StopIteration:
    print("Uuuh not found.")

If value = next... errors your print("Uuuh not found.") will be executed, if not your then your if/else will.

You can have multiple elif's but you must start with an if:

if something:
  ...
elif something_else:
   ....
elif .....

Another option is to use a default value with next then use if/elif/else, if we get no name matched next will return None so we check if value is not None, if it is we print "Uuuh not found." or else we got a matched name so we go to the elif/else :

value = next((e["value"] for e in my_list if e["name"] == name), None)
if value is None:
    print("Uuuh not found.")
elif value % 2:
    print("Odd !")
else:
    print("Even !")


来源:https://stackoverflow.com/questions/32115375/why-does-python-not-implement-the-elif-statement-on-try-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!