Search code examples
pythonpython-3.xpython-3.9contextmanagerwalrus-operator

yield with walrus operator := causes syntax error


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


Solution

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

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