1
import asyncio
from asyncio import StreamReader

async def echo(reader: StreamReader):
    try:
        while data := await reader.readline():
            pass

Question> why we have to data := await here instead of data = await?

Error from python compiler:

while data = await reader.readline():
           ^ SyntaxError: invalid syntax
q0987
  • 34,938
  • 69
  • 242
  • 387

1 Answers1

4

Assignment with = was designed expressly to not do this kind of nested side-effecting inside a larger expression. With other languages (looking at you, C) people can type = where they meant to use == and assign something by accident. See this question for more discussion of why = was designed this way.

Assignment with = is a statement and not an expression, it does not evaluate to what's on the right hand side of the equal sign. That means there isn't a value for the while to test in order to decide whether to continue. The := (AKA the walrus operator) provides a value the while can test, see this question.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276