[Python-ideas] Documenting Python warts (original) (raw)
Chris Angelico rosuav at gmail.com
Wed Jan 2 11:01:57 CET 2013
- Previous message: [Python-ideas] Documenting Python warts
- Next message: [Python-ideas] Documenting Python warts
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Wed, Jan 2, 2013 at 8:49 PM, Steven D'Aprano <steve at pearwood.info> wrote:
On 02/01/13 20:37, Chris Angelico wrote:
Calling it "else" makes perfect sense if you're searching for something.
for x in lst: if x.iswhatwewant(): break else: x=thing() lst.append(x) Not really. The "else" doesn't match the "if", it matches the "for". That's the problem really. Besides, your example is insufficiently general. You can't assume that the "else" immediately follows the "if", let alone the correct if. for x in lst: if x.iswhatwewant(): break dosomething() andanotherthing() if today is Tuesday: print("we must be in Belgium") else: x = thing() lst.append(x) So at best it makes imperfect sense, sometimes.
Thinking functionally, the for loop is searching for an element in the list. It'll either find something (and break) or not find anything (and raise StopIteration). If it finds something, do stuff and break, else do other stuff. The "else" of the logic corresponds to the "else:" clause.
Not saying it's always right, but it does at least make some sense in that particular application, which is a reasonably common one. I've coded exactly that logic in C++, using a goto to do a "break and skip the else clause" (with a comment to the effect that I'd rather be writing Python...).
ChrisA
- Previous message: [Python-ideas] Documenting Python warts
- Next message: [Python-ideas] Documenting Python warts
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]