Home > Enterprise >  yield with walrus operator := causes syntax error
yield with walrus operator := causes syntax error

Time:10-22

import contextlib
from win32com.client import Dispatch  

@contextlib.contextmanager
def excel_ctx() -> Generator[Dispatch, None, None] :
    try:
        yield excel := Dispatch("Excel.Application")
    finally:
        excel.quit()

Is meant to create a new Excel App and call its quit method every time. I thought it could be written more concisely with the walrus operator, but I get SyntaxError: invalid syntax

CodePudding user response:

You need to add parenthesis around the walrus operator like this:

yield (excel := Dispatch("Excel.Application"))
  • Related