[New-bugs-announce] [issue45975] Simplify some while-loops with walrus operator

Nick Drozd report at bugs.python.org
Fri Dec 3 18:15:50 EST 2021


New submission from Nick Drozd <nicholasdrozd at gmail.com>:

The following pattern occurs a few times in the codebase:

  while 1:
      data = conn.recv(blocksize)
      if not data:
          break
      ...

There is an unbounded while loop in which some kind of input is read. If the input is there, it is processed and the loop is continued; otherwise the loop is broken.

This can be expressed more cleanly with the walrus operator:

  while data := conn.recv(blocksize):
     ...

Some of this code goes back to the days of Python 1. I assume that the original authors would have used the walrus idiom if it had been available, which it wasn't. But now it is.

Rewriting the instances of this pattern shaves off 148 lines from the codebase. Removing the manual break statements makes the logic more straightforward.

This should not change the behavior of anything. I'm assuming that this code is all under test and that any deviations from the existing behavior will be caught. Anything that isn't tested shouldn't be changed (and should be tested).

----------
components: Library (Lib)
messages: 407615
nosy: nickdrozd
priority: normal
pull_requests: 28133
severity: normal
status: open
title: Simplify some while-loops with walrus operator
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45975>
_______________________________________


More information about the New-bugs-announce mailing list