[Python-ideas] Add contextlib.DummyContext

Devin Jeanpierre jeanpierreda at gmail.com
Wed May 18 01:36:37 EDT 2016

> This is one of those things which are so easy to implement which makes you
> think it is probably not worth adding to the stdlib, but then again, this is
> something I've ended up doing and rewriting pretty often over the years.
> Real world example:
> class DummyLock(object):
>     def __init__(self, *args, **kwargs):
>         pass
>     def __enter__(self, *args, **kwargs):
>         return self
>     def __exit__(self, *args, **kwargs):
>          pass
> def get_lock(name, bypass_lock=False):
>     lock_cls = DummyLock if bypass_lock else RedisLock
>     return lock
> with get_lock('foo', bypass_lock=True):
>     ...

with contextlib.ExitStack() as exit_stack:
  if not bypass_lock:

And similar.

In fact, ExitStack can itself be used as a no-op context manager, if you want.

-- Devin

More information about the Python-ideas mailing list