[Python-ideas] PEP 572: Assignment Expressions (post #4)

Nick Coghlan ncoghlan at gmail.com
Thu Apr 12 09:02:01 EDT 2018


On 12 April 2018 at 22:22, Jacco van Dorp <j.van.dorp at deonet.nl> wrote:
> I've looked through PEP 343, contextlib docs (
> https://docs.python.org/3/library/contextlib.html ), and I couldn't
> find a single case where "with (y := f(x))" would be invalid.

Consider this custom context manager:

    @contextmanager
    def simple_cm():
        yield 42

Given that example, the following code:

    with cm := simple_cm() as value:
        print(cm.func.__name__, value)

would print "'simple_cm 42", since the assignment expression would
reference the context manager itself, while the with statement binds
the yielded value.

Another relevant example would be `contextlib.closing`: that returns
the passed in argument from __enter__, *not* self.

And that's why earlier versions of PEP 572 (which used the "EXPR as
NAME" spelling) just flat out prohibited top level name binding
expressions in with statements: "with (expr as name):" and "with expr
as name:" were far too different semantically for the only syntactic
difference to be a surrounding set of parentheses.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list