4 ms·
You can actually use else for try statements. Doesn't answer question but it's something I learned relatively recently and may help some others. try:
by figgis 8y ago
You can actually use else for try statements. Doesn't answer question but it's something I learned relatively recently and may help some others.
try:
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy)
except ImportError:
pass
else:
print("well that didn't work")
- pmontra 8y agoI'm not sure about what the message in that print() refers to (else fires if the import succeeded) so here's another example $ python3 >>> try: 1/0 except ZeroDivisionError: print("exception") else: print("surprise") exception >>> try: 1/1 except ZeroDivisionError: print("exception") else: print("normal") 1.0 normal The choice of the name else is unfortunate because it's activated under the same circumstances of a then branch of an "if". Maybe its name should really be "then". That would also look like a .then of a JavaScript Promise, which would make sense nowadays and was obviously impossible to foresee back in 1991. However the name "else" makes sense if it refers to "except": it's what happens when no "except" fire. I still don't understand why it should be "else" for a "for" that succeeded: it should be a "then" there.
- saurik 8y agoIn the case of a for loop, you are modeling "a for which did not break". The cases where you want that block are typically when you are looping through a list trying to find something, so "if I found it I broke, else do this default logic".
- pmontra 8y agoThat's the intended use case but it works also when there is no break $ python3 >>> for i in [1,2,3]: print(i) else: print("completed") 1 2 3 completed That should be a "then", but admittedly a very useless one. I agree that for the intended use case "else" is a better choice. It's like the else of the if that failed to find 2 in this code: >>> for i in [1,2,3]: if i == 2: break else: print("we didn't find 2") Still "else" doesn't hint much at what's going on, especially if the body of the loop is long. Maybe "nobreak" would make it immediately understandable to everybody? However in the best Python tradition I would make it very explicit, remove the feature from the language and use boolean flags. They are less compact but easier to understand than a feature that (probably) very few people know about. >>> we_found_2 = False # this is a valid assertion now >>> for i in [1,2,3]: if i == 2: we_found_2 = True break if not we_found_2: print("we didn't find 2") That's also the only way to do it if there are multiple break in the loop on different conditions.
- figgis 8y agoyeah you are right, it should be print("well that's done")