[Python-ideas] unpacking context managers in WITH statement

Serhiy Storchaka storchaka at gmail.com
Sat Feb 4 22:17:49 CET 2012

03.02.12 17:09, Yury Selivanov написав(ла):
> With the removal of "contextlib.nested" in python 3.2 nothing was introduced to replace it.  However, I found it pretty useful, despite the fact that it had its own quirks.  These quirks can (at least partially) be addressed by allowing unpacking syntax in the context manager.
> Consider the following snipped of code:
>    ctxs = ()
>    if args.profile:
>        ctxs += (ApplicationProfilerContext(),)
>    if args.logging:
>        ctxs += (ApplicationLoggingContext(),)
>    with *ctxs:
>        Application.run()
> As of now, without "nested" we have either option of reimplementing it, or to write lots of ugly code with nested 'try..except's.  So the feature was taken out, but nothing replaced it.

  class EmptyContext:
      def __enter__(self): return self
      def __exit__(self, exc_type, exc_value, traceback): pass

  with ApplicationProfilerContext() if args.profile else EmptyContext():
      with ApplicationLoggingContext() if args.logging else EmptyContext():

Of cause, it will be better to use some special singleton value (None, False or ellipsis) instead EmptyContext(). If any false value would mean an empty context, we will be able to use "with args.profile and ApplicationProfilerContext()" idiom.

More information about the Python-ideas mailing list