yield with walrus 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()

意思是新建一个ExcelApp,每次调用它的quit方法。我认为它可以用海象运算符写得更简洁,但我得到 SyntaxError: invalid syntax

您需要像这样在海象运算符周围添加括号:

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