Re: [Python-ideas] Conditional context manager
Resending, because Google Groups messes up replying to the list :-( On 1 October 2016 at 21:09, Paul Moore
On 1 October 2016 at 19:07, Neil Girdhar
wrote: 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()
This sounds like exactly the sort of situation ExitStack was designed for. I'm not sure the situation is common enough to need dedicated syntax beyond that. I actually find the ExitStack version easier to understand, as the condition is more visible when it's not tucked away at the end of the with statement.
If compactness is that important, you could refactor the code to use a custom context manager that encapsulates the "cm_function if condition else nothing" pattern.
Paul
participants (1)
-
Paul Moore