On 12 April 2018 at 22:22, Jacco van Dorp <j.van.d...@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:
Given that example, the following code:
with cm := simple_cm() as 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.
Nick Coghlan | ncogh...@gmail.com | Brisbane, Australia
Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/