[Python-ideas] Conditional context manager
Neil Girdhar
mistersheik at gmail.com
Sat Oct 1 14:07:25 EDT 2016
I'm just throwing this idea out there to get feedback.
Sometimes, I want to conditionally enter a context manager. This simplest
(afaik) way of doing that is:
with ExitStack() as stack:
if condition:
cm = stack.enter_context(cm_function())
suite()
I suggest a more compact notation:
with cm_function() as cm if condition:
suite()
I'm not sure that this is possible within the grammar. (For some reason
with with_expr contains '"as" expr' rather than '"as" NAME'?
I realize this comes up somewhat rarely. I use context managers a lot, and
it comes up maybe 1 in 5k lines of code.
For some extensions of this notation, an else clause could bind a value to
cm in the case that condition is false.
Best,
Neil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161001/52f854b3/attachment.html>
More information about the Python-ideas
mailing list