Skip to content

Commit 024ac54

Browse files
authored
bpo-45975: Simplify some while-loops with walrus operator (GH-29347)
1 parent 25bc115 commit 024ac54

28 files changed

+41
-153
lines changed

Diff for: Lib/_pyio.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -638,10 +638,7 @@ def read(self, size=-1):
638638
def readall(self):
639639
"""Read until EOF, using multiple read() call."""
640640
res = bytearray()
641-
while True:
642-
data = self.read(DEFAULT_BUFFER_SIZE)
643-
if not data:
644-
break
641+
while data := self.read(DEFAULT_BUFFER_SIZE):
645642
res += data
646643
if res:
647644
return bytes(res)

Diff for: Lib/base64.py

+3-12
Original file line numberDiff line numberDiff line change
@@ -508,25 +508,16 @@ def b85decode(b):
508508

509509
def encode(input, output):
510510
"""Encode a file; input and output are binary files."""
511-
while True:
512-
s = input.read(MAXBINSIZE)
513-
if not s:
514-
break
515-
while len(s) < MAXBINSIZE:
516-
ns = input.read(MAXBINSIZE-len(s))
517-
if not ns:
518-
break
511+
while s := input.read(MAXBINSIZE):
512+
while len(s) < MAXBINSIZE and (ns := input.read(MAXBINSIZE-len(s))):
519513
s += ns
520514
line = binascii.b2a_base64(s)
521515
output.write(line)
522516

523517

524518
def decode(input, output):
525519
"""Decode a file; input and output are binary files."""
526-
while True:
527-
line = input.readline()
528-
if not line:
529-
break
520+
while line := input.readline():
530521
s = binascii.a2b_base64(line)
531522
output.write(s)
532523

Diff for: Lib/ctypes/_aix.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -108,12 +108,8 @@ def get_ld_headers(file):
108108
p = Popen(["/usr/bin/dump", f"-X{AIX_ABI}", "-H", file],
109109
universal_newlines=True, stdout=PIPE, stderr=DEVNULL)
110110
# be sure to read to the end-of-file - getting all entries
111-
while True:
112-
ld_header = get_ld_header(p)
113-
if ld_header:
114-
ldr_headers.append((ld_header, get_ld_header_info(p)))
115-
else:
116-
break
111+
while ld_header := get_ld_header(p):
112+
ldr_headers.append((ld_header, get_ld_header_info(p)))
117113
p.stdout.close()
118114
p.wait()
119115
return ldr_headers

Diff for: Lib/email/parser.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,7 @@ def parse(self, fp, headersonly=False):
4949
feedparser = FeedParser(self._class, policy=self.policy)
5050
if headersonly:
5151
feedparser._set_headersonly()
52-
while True:
53-
data = fp.read(8192)
54-
if not data:
55-
break
52+
while data := fp.read(8192):
5653
feedparser.feed(data)
5754
return feedparser.close()
5855

Diff for: Lib/ftplib.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -434,10 +434,7 @@ def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
434434
"""
435435
self.voidcmd('TYPE I')
436436
with self.transfercmd(cmd, rest) as conn:
437-
while 1:
438-
data = conn.recv(blocksize)
439-
if not data:
440-
break
437+
while data := conn.recv(blocksize):
441438
callback(data)
442439
# shutdown ssl layer
443440
if _SSLSocket is not None and isinstance(conn, _SSLSocket):
@@ -496,10 +493,7 @@ def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):
496493
"""
497494
self.voidcmd('TYPE I')
498495
with self.transfercmd(cmd, rest) as conn:
499-
while 1:
500-
buf = fp.read(blocksize)
501-
if not buf:
502-
break
496+
while buf := fp.read(blocksize):
503497
conn.sendall(buf)
504498
if callback:
505499
callback(buf)

Diff for: Lib/http/client.py

+3-13
Original file line numberDiff line numberDiff line change
@@ -578,11 +578,7 @@ def _read_chunked(self, amt=None):
578578
assert self.chunked != _UNKNOWN
579579
value = []
580580
try:
581-
while True:
582-
chunk_left = self._get_chunk_left()
583-
if chunk_left is None:
584-
break
585-
581+
while (chunk_left := self._get_chunk_left()) is not None:
586582
if amt is not None and amt <= chunk_left:
587583
value.append(self._safe_read(amt))
588584
self.chunk_left = chunk_left - amt
@@ -998,10 +994,7 @@ def send(self, data):
998994
encode = self._is_textIO(data)
999995
if encode and self.debuglevel > 0:
1000996
print("encoding file using iso-8859-1")
1001-
while 1:
1002-
datablock = data.read(self.blocksize)
1003-
if not datablock:
1004-
break
997+
while datablock := data.read(self.blocksize):
1005998
if encode:
1006999
datablock = datablock.encode("iso-8859-1")
10071000
sys.audit("http.client.send", self, datablock)
@@ -1031,10 +1024,7 @@ def _read_readable(self, readable):
10311024
encode = self._is_textIO(readable)
10321025
if encode and self.debuglevel > 0:
10331026
print("encoding file using iso-8859-1")
1034-
while True:
1035-
datablock = readable.read(self.blocksize)
1036-
if not datablock:
1037-
break
1027+
while datablock := readable.read(self.blocksize):
10381028
if encode:
10391029
datablock = datablock.encode("iso-8859-1")
10401030
yield datablock

Diff for: Lib/http/cookiejar.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -1915,9 +1915,7 @@ def _really_load(self, f, filename, ignore_discard, ignore_expires):
19151915
"comment", "commenturl")
19161916

19171917
try:
1918-
while 1:
1919-
line = f.readline()
1920-
if line == "": break
1918+
while (line := f.readline()) != "":
19211919
if not line.startswith(header):
19221920
continue
19231921
line = line[len(header):].strip()
@@ -2017,12 +2015,9 @@ def _really_load(self, f, filename, ignore_discard, ignore_expires):
20172015
filename)
20182016

20192017
try:
2020-
while 1:
2021-
line = f.readline()
2018+
while (line := f.readline()) != "":
20222019
rest = {}
20232020

2024-
if line == "": break
2025-
20262021
# httponly is a cookie flag as defined in rfc6265
20272022
# when encoded in a netscape cookie file,
20282023
# the line is prepended with "#HttpOnly_"

Diff for: Lib/mailbox.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -1956,10 +1956,7 @@ def readlines(self, sizehint=None):
19561956

19571957
def __iter__(self):
19581958
"""Iterate over lines."""
1959-
while True:
1960-
line = self.readline()
1961-
if not line:
1962-
return
1959+
while line := self.readline():
19631960
yield line
19641961

19651962
def tell(self):

Diff for: Lib/mailcap.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -90,9 +90,7 @@ def _readmailcapfile(fp, lineno):
9090
the viewing command is stored with the key "view".
9191
"""
9292
caps = {}
93-
while 1:
94-
line = fp.readline()
95-
if not line: break
93+
while line := fp.readline():
9694
# Ignore comments and blank lines
9795
if line[0] == '#' or line.strip() == '':
9896
continue

Diff for: Lib/mimetypes.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,7 @@ def readfp(self, fp, strict=True):
217217
list of standard types, else to the list of non-standard
218218
types.
219219
"""
220-
while 1:
221-
line = fp.readline()
222-
if not line:
223-
break
220+
while line := fp.readline():
224221
words = line.split()
225222
for i in range(len(words)):
226223
if words[i][0] == '#':

Diff for: Lib/pstats.py

-2
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,6 @@ def get_sort_arg_defs(self):
223223
for word, tup in self.sort_arg_dict_default.items():
224224
fragment = word
225225
while fragment:
226-
if not fragment:
227-
break
228226
if fragment in dict:
229227
bad_list[fragment] = 0
230228
break

Diff for: Lib/pydoc.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -686,9 +686,7 @@ def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
686686
r'RFC[- ]?(\d+)|'
687687
r'PEP[- ]?(\d+)|'
688688
r'(self\.)?(\w+))')
689-
while True:
690-
match = pattern.search(text, here)
691-
if not match: break
689+
while match := pattern.search(text, here):
692690
start, end = match.span()
693691
results.append(escape(text[here:start]))
694692

Diff for: Lib/quopri.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,7 @@ def write(s, output=output, lineEnd=b'\n'):
6767
output.write(s + lineEnd)
6868

6969
prevline = None
70-
while 1:
71-
line = input.readline()
72-
if not line:
73-
break
70+
while line := input.readline():
7471
outline = []
7572
# Strip off any readline induced trailing newline
7673
stripped = b''
@@ -126,9 +123,7 @@ def decode(input, output, header=False):
126123
return
127124

128125
new = b''
129-
while 1:
130-
line = input.readline()
131-
if not line: break
126+
while line := input.readline():
132127
i, n = 0, len(line)
133128
if n > 0 and line[n-1:n] == b'\n':
134129
partial = 0; n = n-1

Diff for: Lib/shlex.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,7 @@ def quote(s):
333333

334334

335335
def _print_tokens(lexer):
336-
while 1:
337-
tt = lexer.get_token()
338-
if not tt:
339-
break
336+
while tt := lexer.get_token():
340337
print("Token: " + repr(tt))
341338

342339
if __name__ == '__main__':

Diff for: Lib/shutil.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -194,10 +194,7 @@ def copyfileobj(fsrc, fdst, length=0):
194194
# Localize variable access to minimize overhead.
195195
fsrc_read = fsrc.read
196196
fdst_write = fdst.write
197-
while True:
198-
buf = fsrc_read(length)
199-
if not buf:
200-
break
197+
while buf := fsrc_read(length):
201198
fdst_write(buf)
202199

203200
def _samefile(src, dst):

Diff for: Lib/smtplib.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -1099,10 +1099,7 @@ def prompt(prompt):
10991099
toaddrs = prompt("To").split(',')
11001100
print("Enter message, end with ^D:")
11011101
msg = ''
1102-
while 1:
1103-
line = sys.stdin.readline()
1104-
if not line:
1105-
break
1102+
while line := sys.stdin.readline():
11061103
msg = msg + line
11071104
print("Message length is %d" % len(msg))
11081105

Diff for: Lib/socketserver.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,7 @@ def handle_request(self):
292292
selector.register(self, selectors.EVENT_READ)
293293

294294
while True:
295-
ready = selector.select(timeout)
296-
if ready:
295+
if selector.select(timeout):
297296
return self._handle_request_noblock()
298297
else:
299298
if timeout is not None:

Diff for: Lib/tarfile.py

+3-9
Original file line numberDiff line numberDiff line change
@@ -1262,11 +1262,7 @@ def _proc_pax(self, tarfile):
12621262
# the newline. keyword and value are both UTF-8 encoded strings.
12631263
regex = re.compile(br"(\d+) ([^=]+)=")
12641264
pos = 0
1265-
while True:
1266-
match = regex.match(buf, pos)
1267-
if not match:
1268-
break
1269-
1265+
while match := regex.match(buf, pos):
12701266
length, keyword = match.groups()
12711267
length = int(length)
12721268
if length == 0:
@@ -2418,10 +2414,8 @@ def _load(self):
24182414
"""Read through the entire archive file and look for readable
24192415
members.
24202416
"""
2421-
while True:
2422-
tarinfo = self.next()
2423-
if tarinfo is None:
2424-
break
2417+
while self.next() is not None:
2418+
pass
24252419
self._loaded = True
24262420

24272421
def _check(self, mode=None):

Diff for: Lib/test/test_lzma.py

+4-16
Original file line numberDiff line numberDiff line change
@@ -825,10 +825,7 @@ def test_read_0(self):
825825
def test_read_10(self):
826826
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
827827
chunks = []
828-
while True:
829-
result = f.read(10)
830-
if not result:
831-
break
828+
while result := f.read(10):
832829
self.assertLessEqual(len(result), 10)
833830
chunks.append(result)
834831
self.assertEqual(b"".join(chunks), INPUT)
@@ -911,10 +908,7 @@ def test_read_bad_data(self):
911908
def test_read1(self):
912909
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
913910
blocks = []
914-
while True:
915-
result = f.read1()
916-
if not result:
917-
break
911+
while result := f.read1():
918912
blocks.append(result)
919913
self.assertEqual(b"".join(blocks), INPUT)
920914
self.assertEqual(f.read1(), b"")
@@ -926,21 +920,15 @@ def test_read1_0(self):
926920
def test_read1_10(self):
927921
with LZMAFile(BytesIO(COMPRESSED_XZ)) as f:
928922
blocks = []
929-
while True:
930-
result = f.read1(10)
931-
if not result:
932-
break
923+
while result := f.read1(10):
933924
blocks.append(result)
934925
self.assertEqual(b"".join(blocks), INPUT)
935926
self.assertEqual(f.read1(), b"")
936927

937928
def test_read1_multistream(self):
938929
with LZMAFile(BytesIO(COMPRESSED_XZ * 5)) as f:
939930
blocks = []
940-
while True:
941-
result = f.read1()
942-
if not result:
943-
break
931+
while result := f.read1():
944932
blocks.append(result)
945933
self.assertEqual(b"".join(blocks), INPUT * 5)
946934
self.assertEqual(f.read1(), b"")

Diff for: Lib/urllib/request.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -265,10 +265,7 @@ def urlretrieve(url, filename=None, reporthook=None, data=None):
265265
if reporthook:
266266
reporthook(blocknum, bs, size)
267267

268-
while True:
269-
block = fp.read(bs)
270-
if not block:
271-
break
268+
while block := fp.read(bs):
272269
read += len(block)
273270
tfp.write(block)
274271
blocknum += 1
@@ -1847,10 +1844,7 @@ def retrieve(self, url, filename=None, reporthook=None, data=None):
18471844
size = int(headers["Content-Length"])
18481845
if reporthook:
18491846
reporthook(blocknum, bs, size)
1850-
while 1:
1851-
block = fp.read(bs)
1852-
if not block:
1853-
break
1847+
while block := fp.read(bs):
18541848
read += len(block)
18551849
tfp.write(block)
18561850
blocknum += 1

Diff for: Lib/wsgiref/handlers.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -475,10 +475,7 @@ def _write(self,data):
475475
from warnings import warn
476476
warn("SimpleHandler.stdout.write() should not do partial writes",
477477
DeprecationWarning)
478-
while True:
479-
data = data[result:]
480-
if not data:
481-
break
478+
while data := data[result:]:
482479
result = self.stdout.write(data)
483480

484481
def _flush(self):

Diff for: Lib/wsgiref/validate.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -214,10 +214,7 @@ def readlines(self, *args):
214214
return lines
215215

216216
def __iter__(self):
217-
while 1:
218-
line = self.readline()
219-
if not line:
220-
return
217+
while line := self.readline():
221218
yield line
222219

223220
def close(self):

0 commit comments

Comments
 (0)