News for hackers. Stuff that matters.
Re:The optional “else” in Python loops by Psyonic on Thursday July 17, 2014 @08:24PM (#8051038)
While in theory this is useful, it's one of the least intuitive parts of python for me. I avoid them whenever possible because I feel "else" conveys the intent very poorly. (And I've been writing python for years.)
Re:The optional “else” in Python loops by simonw on Thursday July 17, 2014 @08:31PM (#8051063)
I agree. Intuitively, I would expect for item in list: .... else: ... to execute the "else" clause only if the list was empty and hence the for loop didn't iterate at all.
Re:The optional “else” in Python loops by wting on Thursday July 17, 2014 @08:42PM (#8051105)
Raymond Hettinger has suggested that instead of `else:` the keyword should have been called `nobreak:` which conveys intentions better.
Re:The optional “else” in Python loops by avn2109 on Thursday July 17, 2014 @11:58PM (#8051593)
What about using "finally," which if IIRC is already a thing in Python and encapsulates this idea pretty neatly?
Re:The optional “else” in Python loops by dbarlett on Friday July 18, 2014 @12:05AM (#8051607)
finally blocks are always executed; this kind of else block is only executed if the for block exited normally (i.e. did not throw an exception).
Re:The optional “else” in Python loops by aperture on Friday July 18, 2014 @01:11AM (#8051765)
How about a keyword such as "after"? I feel like that could have extensible potential in other areas of the language, and the name makes a little sense logically speaking.
Re:The optional “else” in Python loops by gingerrr on Friday July 18, 2014 @04:40AM (#8052167)
or something like "then"?
Re:The optional “else” in Python loops by BerislavLopac on Friday July 18, 2014 @06:22AM (#8052365)
Or "unbroken", even... ;-)
Re:The optional “else” in Python loops by thatswrong0 on Thursday July 17, 2014 @08:30PM (#8051056)
I agree. I use it, but intuitively, I think of else acting the opposite way - if the loop finishes successfully, great! else, do something.
Re:The optional “else” in Python loops by eurleif on Thursday July 17, 2014 @08:32PM (#8051065)
If you're using break to signal success, that is how else acts.
Re:The optional “else” in Python loops by thatswrong0 on Thursday July 17, 2014 @08:41PM (#8051102)
I've been using break to signal failure. I'll keep that in mind.
Re:The optional “else” in Python loops by maxerickson on Thursday July 17, 2014 @08:45PM (#8051113)
Just to illustrate:

    >>> for item in (1,2):
    	print(item)
    else:
    	print('Done!')

    1
    2
    Done!
    >>> for item in (1,2):
    	print(item)
    	break
    else:
    	print('Done!')
    
    1
    >>>
edit: also:

    >>> for item in ():
    	print(item)
    else:
    	print('Done')
    
    Done
Re:The optional “else” in Python loops by blahedo on Thursday July 17, 2014 @11:46PM (#8051567)
What's more, it dances very close to something that is a super-common error for novice programmers: the early return from a loop. I grade AP exams every year, and one of the hands-down most common conceptual mistakes I've seen (on problems where this is relevant) goes something like this:

    boolean lookForSomething(int parameter) {
      for (Item item: list) {
        if (item.matches(parameter))
          return true;
        else
          return false;
      }
    }
where a correct answer would omit the "else" and put the "return false;" outside the bracketed loop (or, keep a boolean variable updated and then return that after the loop is done. Let's translate that to python:

    def lookForSomething(parameter):
      for item in list:
        if matches(item, parameter):
          return true
        else:
          return false
As a conceptual matter, for a beginner who is still trying to nail down the whole notion of "can stop early when found, but have to scan the whole list if not found", it is just plain nasty that the following code is not only correct but idiomatic:

    def lookForSomething(parameter):
      for item in list:
        if matches(item, parameter):
          return true
      else:
        return false
Re:The optional “else” in Python loops by chrismorgan on Friday July 18, 2014 @12:58AM (#8051741)
That last one is not idiomatic (I’ll ignore the lowercase first letter of True and False).

The `else` there is superfluous; that cuts it down to this:

    def look_for_something(parameter):
        for item in list:
            if matches(item, parameter):
                return True
        return False
And then after that one should just replace the entire loop with an `any` call:

    def look_for_something(parameter):
        return any(matches(item, parameter) for item in list)
Also, if we assume a `matches()` that is simple equality, then it would just be

    def look_for_something(parameter):
        return parameter in list
… and even then, you shouldn’t have named a variable `list`.

Cut down to its essence like this, the function probably shouldn’t have even existed… ☺

Re:The optional “else” in Python loops by blahedo on Friday July 18, 2014 @04:12AM (#8052115)
Remember that I was talking about novice programmers, here. I'll concede that "idiomatic" was a bit strong (and the True/False thing was a brain fart), but I think my main point stands: encouraging the use of an "else:" that can attach to loops, with an unobvious and somewhat nuanced semantics, is not kind to newcomers. And the fact remains that the difference between a correct implementation and one that is wrong in exactly the way that a lot of newcomers get it wrong is nothing but indentation.
Re:The optional “else” in Python loops by stbarnes on Friday July 18, 2014 @09:29AM (#8052878)
The 'else' after the 'if' is unnecessary, but so what? We're not running out of letters. IMO including an "else" makes it clearer.
Re:The optional “else” in Python loops by enneff on Thursday July 17, 2014 @11:41PM (#8051555)
I totally agree. I wrote Python code professionally for five years and am shocked to find I was wrong about this all this time. I must have introduced quite a few bugs. :-/
Re:The optional “else” in Python loops by MBlume on Thursday July 17, 2014 @08:33PM (#8051074)
What finally made it intuitive for me: assuming the loop contains an if condition: break, you can consider the else-clause to be the else of the if statement within the loop.
Re:The optional “else” in Python loops by pyre on Thursday July 17, 2014 @11:41PM (#8051557)
I think the real issue is that the word 'else' is ambiguous in the context. Everyone comes in with a different idea of what the 'else' is a fallback clause to. Guido obviously picked one particular case, but there are other valid meanings.

For example, I think that it's more common to want to do something like:

  # mnemonic:
  #   for thing in list_of_things DO_SOMETHING else DO_SOMETHING_ELSE

  if list_of_things:
    for thing in list_of_things:
      print thing
  else:
    print "No things!"
Than:

  for thing in list_of_things:
    if thing.is_awesome:
      break
  else:
    print "No awesome things!"
And what about conditional code that you want to execute when a loop does break early?

  error_found = False

  for thing in list_of_things:
    if thing.error_condition:
      error_found = True
      break

  if error_found:
    pass
Re:The optional “else” in Python loops by collyw on Friday July 18, 2014 @03:52AM (#8052083)
That makes sense on one level, but when you consider Pythons indenting rules, it just messes everything up.
Re:The optional “else” in Python loops by pyre on Friday July 18, 2014 @01:32PM (#8054368)
I'm not sure how the indentation rules come into play here. I'm not saying that this:

  if blah:
    for .. in ..:
      ..
  else:
    ..
is visually confused with:

  for .. in ..:
    ..
  else:
    ..
What I'm saying is that for-else and while-else add syntax to the language that only solves a single specific instance of a class of similar issues, making it confusing.

Let's consider the issues that are in the same class:

- execute code block when loop condition isn't met the first time (i.e. loop never executes).

- execute code block when loop exits prematurely (e.g. break).

- execute code block when loop doesn't exit prematurely (e.g. no break) // execute code block when loop condition evals to false (first eval or any subsequent eval)

Only one of these issues is solved by the for-else/while-else syntax currently in Python, and using a generic keyword (else) just heightens the confusion (especially since this syntax differs from many other languages).

All of these cases may require the use of sentinels / additional checks to implement. Why is one specific instance any more relevant than the others to the point that it gets special treatment (i.e. special syntax in the core language)?

Re:The optional “else” in Python loops by BWStearns on Thursday July 17, 2014 @08:41PM (#8051103)
That logic definitely helps me think about it. But it does seem like a switch from the other wording that python uses. Feels like finally would be more intuitive, whereas without thinking about the search loop case else feels like something that would be triggered by a break or return. I wonder if using the feature would be more common if it was more intuitively worded.
Re:The optional “else” in Python loops by maxerickson on Thursday July 17, 2014 @10:23PM (#8051351)
It's analogous to the natural termination of a while-else, where the else block is executed after the condition evaluates to false:

    >>> a=1
    >>> while a>0:
        print(4)
        a=a-1
    else:
        print('done')
        
    4
    done
clarity cribbed from here: https://mail.python.org/pipermail/python-list/1999-July/0044...
Re:The optional “else” in Python loops by MBlume on Friday July 18, 2014 @07:44PM (#8056134)
Oh, that helps too -- it's an else clause for the conditional of the while loop :D
Re:The optional “else” in Python loops by MBlume on Friday July 18, 2014 @07:40PM (#8056126)
finally seems much more confusing to me -- the point of finally is that it will definitely be executed...