You can use an ExitStack for this

On Wed, May 18, 2016 at 1:29 AM, Giampaolo Rodola' <> wrote:
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):
    def __enter__(self, *args, **kwargs):
        return self
    def __exit__(self, *args, **kwargs):

def get_lock(name, bypass_lock=False):
    lock_cls = DummyLock if bypass_lock else RedisLock
    return lock

with get_lock('foo', bypass_lock=True):

Similarly to contextlib.closing and contextlib.suppress, perhaps it would be nice to have contextlib.DummyContext just because it's something which is done (I think) fairly often.

On the bikeshedding front, in order to be consistent with closing(), redirect_stderr(), redirect_stdout() and suppress(), a better name for this would probably be contextlib.dummy_context.

Extra: the same thing can be achieved by using mock.MagicMock, which probably makes this proposal useless and kills it entirely. The additional value is that it would be more explicit/clear/immediate to have this in contextlib itself as opposed to unittest module, which is kinda weird. But then again, "there should be (possibly) only one way to do it" so I'm not sure. 
OK, I should stop talking with myself. =) 


Python-ideas mailing list
Code of Conduct: