Live data from Hacker News

A Python Guide for the Ages

gto76.github.io

21–30 of 59 posts

Re: A Python Guide for the Ages

#21
post #9

Earlier quoted context omitted.

It’s consistent with try…else and if…else so I actually think it’s ok.

"else" usually means "instead of" or "otherwise" in those patterns. If the original case doesn't run, then the else case runs instead. In a for loop, the else clause only runs if the loop successfully completes (isn't broken), so the else in for-else means the total opposite of what it means in every other pattern. I think it would make a lot more sense if it were replaced with "done" or "upon" or something else that…

The way you describe is how it worked in zope templates (allowing a 'no items here' text if there was nothing to iterate over in a list) - it was frustrating that the later python implementation was different.

Re: A Python Guide for the Ages

#23

There are a couple of language features in Python that I thought were cool when I discovered them, but actually have never ever find a need for them in my code. The first is using an "else" clause in a "for" loop, and the second is returning a value from a generator. Curious whether anybody actually uses either of those.

for/else is unfortunately named (although makes sense if you think about the hidden if/else in a loop). It is essentially use to distinguish between "this loop ended naturally" (the else condition) or "this loop was broken".

I used it recently in some mutating code in which I wanted to make a change, and also know if it did actually make a change. If the routine gets to the end of the loop without finding a place to make a change, it hits the "else" and returns False.

Re: A Python Guide for the Ages

#25
post #4

There are a couple of language features in Python that I thought were cool when I discovered them, but actually have never ever find a need for them in my code. The first is using an "else" clause in a "for" loop, and the second is returning a value from a generator. Curious whether anybody actually uses either of those.

I actually saw someone use that for-else pattern in advent of code earlier this month. I believe the consensus was that it was definitely the perfect choice for the given use case, but neither he nor I would ever dare use it in production because nobody knows about it and it's super unintuitive. I think the idea is cool (albeit rarely useful), but a different word than "else" for the same functionality would go a lon…

Instead of avoiding it in production code, it's better to understand that it's the perfect place for a comment. For example:

   for ...:
      ...
   else:
      # loop ended, no positions found
      return ...

Re: A Python Guide for the Ages

#26
I'm surprised to see mutable default values not mentioned. It's bitten me more than once to discover that:

    def f(xs = []):
        xs.append(5)
        return xs
    
    print(f())
    print(f())
will print:

    [5]
    [5,5]
and I love python despite this horrendous decision, but it should be mentioned more often in beginner resources.

edit: thanks for the downvote? I've answered on the order of dozens of questions about this very mechanic on SO, via IRC, and more... it's a well-known confusing factor

Re: A Python Guide for the Ages

#27
post #10

Earlier quoted context omitted.

I prefer using the else clause to maintaining an "is_found" flag. Although this is lesser known syntax so I probably wouldn't use it when multiple developers are involved.

Yeah, the biggest risk with for-else is that some inexperienced dev comes along and misreads the else as belonging to an if statement inside the for (or, worse, attempting to “fix” it). I’ve seen this happen more than once…

Yes I always comment on it for this reason, sometimes (if I know the code will be maintained by someone with less python experience) with a link to the standard doc.

It's actually a super useful pattern for any kind of search iteration. I've used it many times.

Re: A Python Guide for the Ages

#28

There are a couple of language features in Python that I thought were cool when I discovered them, but actually have never ever find a need for them in my code. The first is using an "else" clause in a "for" loop, and the second is returning a value from a generator. Curious whether anybody actually uses either of those.

for/else is actually super useful for searching through a sequence or for iterating with a possible failure. Something like,

  for i in range(n):
      if search(i) == val:
          break
  else:
      raise KeyError("not found")
  found_index = i
It reduces the need for an additional flag. More importantly it makes it easier to ensure that the break condition is satisfied such that the loop variable can be used properly later on. Personally, I think an else condition should almost always be there for loops that gets broken early, similarly to always finishing if else chain with a final else.

ETA: Another pattern where it's really useful is to replace

  while True:
with a safer guaranteed terminating loop,

  for i in range(MAX_ITER):
     ...
  else:
    raise RuntimeError("exceeded max iterations")
Post reply on HN