[Python-ideas] Conditional context manager
Paul Moore
p.f.moore at gmail.com
Sat Oct 1 16:11:14 EDT 2016
Resending, because Google Groups messes up replying to the list :-(
On 1 October 2016 at 21:09, Paul Moore <p.f.moore at gmail.com> wrote:
> On 1 October 2016 at 19:07, Neil Girdhar <mistersheik at gmail.com> 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
More information about the Python-ideas
mailing list