[Python-Dev] Assignment expression and coding style: the while True case
Victor Stinner
vstinner at redhat.com
Wed Jul 4 20:03:23 EDT 2018
On the 3360 for loops of the stdlib (*), I only found 2 loops which
would benefit of assignment expressions.
It's not easy to find loops which:
- build a list,
- are simple enough to be expressed as list comprehension,
- use a condition (if),
- use an expression different than just a variable name as the list
value (value appended to the list).
diff --git a/Lib/mailbox.py b/Lib/mailbox.py
index 056251dce0..dc61a3a8b6 100644
--- a/Lib/mailbox.py
+++ b/Lib/mailbox.py
@@ -1341,9 +1341,9 @@ class Babyl(_singlefileMailbox):
if len(stops) < len(starts):
stops.append(line_pos - len(linesep))
starts.append(next_pos)
- labels = [label.strip() for label
- in
self._file.readline()[1:].split(b',')
- if label.strip()]
+ labels = [slabel for label
+ in self._file.readline()[1:].split(b',')
+ if (slabel := label.strip())]
label_lists.append(labels)
elif line == b'\037' or line == b'\037' + linesep:
if len(stops) < len(starts):
diff --git a/Lib/nntplib.py b/Lib/nntplib.py
index 5961a28ab7..a5d13e35be 100644
--- a/Lib/nntplib.py
+++ b/Lib/nntplib.py
@@ -843,11 +843,9 @@ class _NNTPBase:
DeprecationWarning, 2)
line_pat = re.compile('^([^ \t]+)[ \t]+(.*)$')
resp, raw_lines = self._longcmdstring('XGTITLE ' + group, file)
- lines = []
- for raw_line in raw_lines:
- match = line_pat.search(raw_line.strip())
- if match:
- lines.append(match.group(1, 2))
+ lines = [match.group(1, 2)
+ for raw_line in raw_lines
+ if (match := line_pat.search(raw_line.strip()))]
return resp, lines
def xpath(self, id):
(*) Command used to count the number of for loops in the stdlib:
$ grep '\bfor\b' Lib/*py
Lib/{asyncio,logging,multiprocessing}/*.py|grep -v '"""'|grep -v
"'''"|grep -v '\.py: *#'|wc -l
3360
Victor
More information about the Python-Dev
mailing list