[Python-Dev] Chaining try statements: eltry? (original) (raw)

BJörn Lindqvist bjourne at gmail.com
Mon Jul 11 11:07:07 CEST 2005


> I surely find them useful, and see them as a Python originality (a > welcome one).

They are indeed an original invention. (One day I looked at the similarity between if and while and noticed that there was a use case for else after while too.) The question remains whether Python would be easier to learn without them. And if so, the question would remain whether that's offset by their utility for experienced developers. All hard to assess impartially!

I dislike them because I can never read looping constructs with else: without thinking hard about what it does. Like:

for x in alist: if x == "foo": break else: print "foo was not found."

Is a better way of doing:

found = False for x in alist: if x == "foo": found = True break if not found: print "foo was not found."

So the else: is taken if the break wasn't executed. I think that is hard to grasp because it makes the for and break into a kind of conditional statement where break makes it evalute to true. But I think the best way to code this silly example is to write:

def finder(): for x in alist: if x == "foo": return True return False if not finder(): print "foo was not found."

Which is how I write when someone else might had used a "else." So IMHO, the use cases are weak. It's also confusing that try: has a different kind of else. "else" in "try" is a good thing - no exception occured. "else" in a for/while is (usually) a bad thing - as item was not found.

-- mvh Björn



More information about the Python-Dev mailing list