Assign variable in while loop condition in Python?

user541686 picture user541686 · Jul 9, 2011 · Viewed 71.4k times · Source

I just came across this piece of code

while 1:
    line = data.readline()
    if not line:
        break
    #...

and thought, there must be a better way to do this, than using an infinite loop with break.

So I tried:

while line = data.readline():
    #...

and, obviously, got an error.

Is there any way to avoid using a break in that situation?

Edit:

Ideally, you'd want to avoid saying readline twice... IMHO, repeating is even worse than just a break, especially if the statement is complex.

Answer

Xavier Guihot picture Xavier Guihot · Apr 27, 2019

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (data.readline()) of the while loop as a variable (line) in order to re-use it within the body of the loop:

while line := data.readline():
  do_smthg(line)