[Python-ideas] Add contextlib.DummyContext
Giampaolo Rodola'
g.rodola at gmail.com
Wed May 18 01:29:40 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):
...
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. =)
--
Giampaolo - http://grodola.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160518/a04c32bb/attachment.html>
More information about the Python-ideas
mailing list