Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions Lib/_pydecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2778,12 +2778,8 @@ def sqrt(self, context=None):

# find n = floor(sqrt(c)) using Newton's method
n = 10**prec
while True:
q = c//n
if n <= q:
break
else:
n = n + q >> 1
while (q := c//n) < n:
n = n + q >> 1
exact = exact and n*n == c

if exact:
Expand Down
5 changes: 1 addition & 4 deletions Lib/_pyio.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,10 +588,7 @@ def read(self, size=-1):
def readall(self):
"""Read until EOF, using multiple read() call."""
res = bytearray()
while True:
data = self.read(DEFAULT_BUFFER_SIZE)
if not data:
break
while (data := self.read(DEFAULT_BUFFER_SIZE)):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you using parentheses here? I don't think they are syntactically necessary.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm too lazy to read the latest PEP, and the current implementation of the PEP is outdated, so I added parenthesis even if they are not needed.

res += data
if res:
return bytes(res)
Expand Down
5 changes: 1 addition & 4 deletions Lib/aifc.py
Original file line number Diff line number Diff line change
Expand Up @@ -943,9 +943,6 @@ def openfp(f, mode=None):
print("Writing", gn)
with open(gn, 'w') as g:
g.setparams(f.getparams())
while 1:
data = f.readframes(1024)
if not data:
break
while (data := f.readframes(1024)):
g.writeframes(data)
print("Done.")
5 changes: 1 addition & 4 deletions Lib/asyncio/sslproto.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,8 @@ def feed_ssldata(self, data, only_handshake=False):

if self._state == _WRAPPED:
# Main state: read data from SSL until close_notify
while True:
chunk = self._sslobj.read(self.max_size)
while (chunk := self._sslobj.read(self.max_size)):
appdata.append(chunk)
if not chunk: # close_notify
break

elif self._state == _SHUTDOWN:
# Call shutdown() until it doesn't raise anymore.
Expand Down
5 changes: 1 addition & 4 deletions Lib/asyncio/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,10 +629,7 @@ async def read(self, n=-1):
# deadlock if the subprocess sends more than self.limit
# bytes. So just call self.read(self._limit) until EOF.
blocks = []
while True:
block = await self.read(self._limit)
if not block:
break
while (block := await self.read(self._limit)):
blocks.append(block)
return b''.join(blocks)

Expand Down
5 changes: 1 addition & 4 deletions Lib/asyncio/windows_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,10 +699,7 @@ def _poll(self, timeout=None):
if ms >= INFINITE:
raise ValueError("timeout too big")

while True:
status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
if status is None:
break
while (status := _overlapped.GetQueuedCompletionStatus(self._iocp, ms)) is not None:
ms = 0

err, transferred, key, address = status
Expand Down
15 changes: 3 additions & 12 deletions Lib/base64.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,25 +490,16 @@ def b85decode(b):

def encode(input, output):
"""Encode a file; input and output are binary files."""
while True:
s = input.read(MAXBINSIZE)
if not s:
break
while len(s) < MAXBINSIZE:
ns = input.read(MAXBINSIZE-len(s))
if not ns:
break
while (s := input.read(MAXBINSIZE)):
while len(s) < MAXBINSIZE and (ns := input.read(MAXBINSIZE-len(s))):
s += ns
line = binascii.b2a_base64(s)
output.write(line)


def decode(input, output):
"""Decode a file; input and output are binary files."""
while True:
line = input.readline()
if not line:
break
while (line := input.readline()):
s = binascii.a2b_base64(line)
output.write(s)

Expand Down
16 changes: 4 additions & 12 deletions Lib/binhex.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,16 +237,12 @@ def binhex(inp, out):

with io.open(inp, 'rb') as ifp:
# XXXX Do textfile translation on non-mac systems
while True:
d = ifp.read(128000)
if not d: break
while (d := ifp.read(128000)):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bigger win than it looks like.

Note that the original "if not d: break" on a single line was itself arguably a style violation because the break doesn't start a line, even though it might change flow-control. That said, I would have done the same thing as the original author to keep it short; it feels like a guard instead of a real control "path".

So this is an area where vertical space matters, the "while True: " is ugly, and the current spelling is already doing slightly ugly things to avoid drawing extra emphasis ... and shortening it with the inline assignment improves on all three.

ofp.write(d)
ofp.close_data()

ifp = openrsrc(inp, 'rb')
while True:
d = ifp.read(128000)
if not d: break
while (d := ifp.read(128000)):
ofp.write_rsrc(d)
ofp.close()
ifp.close()
Expand Down Expand Up @@ -460,19 +456,15 @@ def hexbin(inp, out):

with io.open(out, 'wb') as ofp:
# XXXX Do translation on non-mac systems
while True:
d = ifp.read(128000)
if not d: break
while (d := ifp.read(128000)):
ofp.write(d)
ifp.close_data()

d = ifp.read_rsrc(128000)
if d:
ofp = openrsrc(out, 'wb')
ofp.write(d)
while True:
d = ifp.read_rsrc(128000)
if not d: break
while (d := ifp.read_rsrc(128000)):
ofp.write(d)
ofp.close()

Expand Down
5 changes: 1 addition & 4 deletions Lib/chunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@
except EOFError:
break
chunktype = chunk.getname()
while True:
data = chunk.read(nbytes)
if not data:
pass
while (data := chunk.read(nbytes)):
# do something with data

The interface is file-like. The implemented methods are:
Expand Down
5 changes: 1 addition & 4 deletions Lib/fnmatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,7 @@ def translate(pat):
else:
chunks = []
k = i+2 if pat[i] == '!' else i+1
while True:
k = pat.find('-', k, j)
if k < 0:
break
while (k := pat.find('-', k, j)) >= 0:
chunks.append(pat[i:k])
i = k+1
k = k+3
Expand Down
10 changes: 2 additions & 8 deletions Lib/ftplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,10 +440,7 @@ def retrbinary(self, cmd, callback, blocksize=8192, rest=None):
"""
self.voidcmd('TYPE I')
with self.transfercmd(cmd, rest) as conn:
while 1:
data = conn.recv(blocksize)
if not data:
break
while (data := conn.recv(blocksize)):
callback(data)
# shutdown ssl layer
if _SSLSocket is not None and isinstance(conn, _SSLSocket):
Expand Down Expand Up @@ -502,10 +499,7 @@ def storbinary(self, cmd, fp, blocksize=8192, callback=None, rest=None):
"""
self.voidcmd('TYPE I')
with self.transfercmd(cmd, rest) as conn:
while 1:
buf = fp.read(blocksize)
if not buf:
break
while (buf := fp.read(blocksize)):
conn.sendall(buf)
if callback:
callback(buf)
Expand Down
5 changes: 1 addition & 4 deletions Lib/getpass.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,7 @@ def win_getpass(prompt='Password: ', stream=None):
for c in prompt:
msvcrt.putwch(c)
pw = ""
while 1:
c = msvcrt.getwch()
if c == '\r' or c == '\n':
break
while (c := msvcrt.getwch()) not in ('\r', '\n'):
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
Expand Down
5 changes: 1 addition & 4 deletions Lib/gzip.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,10 +560,7 @@ def _test():
else:
f = builtins.open(arg, "rb")
g = open(arg + ".gz", "wb")
while True:
chunk = f.read(1024)
if not chunk:
break
while (chunk := f.read(1024)):
g.write(chunk)
if g is not sys.stdout.buffer:
g.close()
Expand Down
23 changes: 6 additions & 17 deletions Lib/mailbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,11 +679,8 @@ def flush(self):
self._file.seek(start)
self._pre_message_hook(new_file)
new_start = new_file.tell()
while True:
buffer = self._file.read(min(4096,
stop - self._file.tell()))
if not buffer:
break
while (buffer := self._file.read(min(4096,
stop - self._file.tell()))):
new_file.write(buffer)
new_toc[key] = (new_start, new_file.tell())
self._post_message_hook(new_file)
Expand Down Expand Up @@ -1422,10 +1419,8 @@ def _install_message(self, message):
self._file.write(line.replace(b'\n', linesep))
if line == b'\n' or not line:
break
while True:
buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
if not buffer:
break
# Buffer size is arbitrary.
while (buffer := orig_buffer.read(4096)):
self._file.write(buffer.replace(b'\n', linesep))
elif isinstance(message, (bytes, str, io.StringIO)):
if isinstance(message, io.StringIO):
Expand Down Expand Up @@ -1465,10 +1460,7 @@ def _install_message(self, message):
message.seek(original_pos)
else:
break
while True:
line = message.readline()
if not line:
break
while (line := message.readline()):
# Universal newline support.
if line.endswith(b'\r\n'):
line = line[:-2] + linesep
Expand Down Expand Up @@ -1953,10 +1945,7 @@ def readlines(self, sizehint=None):

def __iter__(self):
"""Iterate over lines."""
while True:
line = self.readline()
if not line:
return
while (line := self.readline()):
yield line

def tell(self):
Expand Down
4 changes: 1 addition & 3 deletions Lib/mailcap.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ def _readmailcapfile(fp, lineno):
the viewing command is stored with the key "view".
"""
caps = {}
while 1:
line = fp.readline()
if not line: break
while (line := fp.readline()):
# Ignore comments and blank lines
if line[0] == '#' or line.strip() == '':
continue
Expand Down
5 changes: 1 addition & 4 deletions Lib/mimetypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,10 +212,7 @@ def readfp(self, fp, strict=True):
list of standard types, else to the list of non-standard
types.
"""
while 1:
line = fp.readline()
if not line:
break
while (line := fp.readline()):
words = line.split()
for i in range(len(words)):
if words[i][0] == '#':
Expand Down
10 changes: 2 additions & 8 deletions Lib/nntplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,19 +481,13 @@ def _getlongresp(self, file=None):
if file is not None:
# XXX lines = None instead?
terminators = (b'.' + _CRLF, b'.\n')
while 1:
line = self._getline(False)
if line in terminators:
break
while (line := self._getline(False)) not in terminators:
if line.startswith(b'..'):
line = line[1:]
file.write(line)
else:
terminator = b'.'
while 1:
line = self._getline()
if line == terminator:
break
while (line := self._getline()) != terminator:
if line.startswith(b'..'):
line = line[1:]
lines.append(line)
Expand Down
5 changes: 1 addition & 4 deletions Lib/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -572,10 +572,7 @@ def _platform(*args):
platform = platform.replace('unknown', '')

# Fold '--'s and remove trailing '-'
while 1:
cleaned = platform.replace('--', '-')
if cleaned == platform:
break
while (cleaned := platform.replace('--', '-')) != platform:
platform = cleaned
while platform[-1] == '-':
platform = platform[:-1]
Expand Down
5 changes: 1 addition & 4 deletions Lib/posixpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,10 +301,7 @@ def expandvars(path):
end = '}'
environ = os.environ
i = 0
while True:
m = search(path, i)
if not m:
break
while (m := search(path, i)):
i, j = m.span(0)
name = m.group(1)
if name.startswith(start) and name.endswith(end):
Expand Down
5 changes: 1 addition & 4 deletions Lib/py_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,7 @@ def main(args=None):
args = sys.argv[1:]
rv = 0
if args == ['-']:
while True:
filename = sys.stdin.readline()
if not filename:
break
while (filename := sys.stdin.readline()):
filename = filename.rstrip('\n')
try:
compile(filename, doraise=True)
Expand Down
4 changes: 1 addition & 3 deletions Lib/pydoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,9 +595,7 @@ def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?(\w+))')
while True:
match = pattern.search(text, here)
if not match: break
while (match := pattern.search(text, here)):
start, end = match.span()
results.append(escape(text[here:start]))

Expand Down
9 changes: 2 additions & 7 deletions Lib/quopri.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,7 @@ def write(s, output=output, lineEnd=b'\n'):
output.write(s + lineEnd)

prevline = None
while 1:
line = input.readline()
if not line:
break
while (line := input.readline()):
outline = []
# Strip off any readline induced trailing newline
stripped = b''
Expand Down Expand Up @@ -126,9 +123,7 @@ def decode(input, output, header=False):
return

new = b''
while 1:
line = input.readline()
if not line: break
while (line := input.readline()):
i, n = 0, len(line)
if n > 0 and line[n-1:n] == b'\n':
partial = 0; n = n-1
Expand Down
8 changes: 1 addition & 7 deletions Lib/re.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,13 +349,7 @@ def scan(self, string):
append = result.append
match = self.scanner.scanner(string).match
i = 0
while True:
m = match()
if not m:
break
j = m.end()
if i == j:
break
while (m := match()) and (j := m.end()) == i:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't that reverse the test on j? As in, shouldn't it be
while (m := match()) and (j := m.end()) != i:

Though I'm not sure which way this argues; the original logic was at least as hard to follow as the new code.

action = self.lexicon[m.lastindex-1][1]
if callable(action):
self.match = m
Expand Down
Loading