[Python-ideas] Proposal: Allowing any variable to be used in a 'with... as...' expression

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Mon May 20 21:56:40 EDT 2019

Robert Collins writes:

 > What you describe sounds like the Maybe monad or the Option enum in
 > Rust to me.
 > with Maybe(expr1) as var1, expr2 as var2, ...:
 >     body
 > doesn't seem ugly to me, and would make clear whether expr1 was
 > something that had to have a value or could, maybe, be None.

AIUI `None` is a red herring.  Yonatan is thinking more generally
about any kind of polymorphism, where not all members of the union are
context managers.  Then he makes the obvious generalization to unions
where none of the members are context managers.

I was also thinking basically along your line, where rather than
having the with construct do checking, having a ContextManagerProxy
(probably to be spelled "CMProxy") factory which would return its
argument unchanged if it was a context manager, and otherwise return a
proxy that contains the argument as a member, provides __enter__ and
__exit__ methods, and proxies all of the other attributes of the
original via __getattribute__ or __getattr__.  Sure, this is less
efficient but I prefer having such behavior explicitly marked.

More information about the Python-ideas mailing list