Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Created November 10, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treyhunner/009fef5d4ed9220d049b08c9cb6a230a to your computer and use it in GitHub Desktop.
Save treyhunner/009fef5d4ed9220d049b08c9cb6a230a to your computer and use it in GitHub Desktop.
Operator precedence walrus operator oddity
"""
while n < 10 and chunk := f.read(256): # SyntaxError
while n < 10 and (chunk := f.read(256)): # Works
while chunk := f.read(256) and n < 10: # chunk will be a boolean 😮
"""
from io import StringIO
f = StringIO("".join(c * 256 for c in "abcdefg")) # File-like object
n = 0
chunks = []
while n < 10 and chunk := f.read(256):
chunks.append(chunk)
n += 1
assert all(type(chunk) is str for chunk in chunks)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment