Message281556
It turns out that there's a variant on the "null context manager" idea that may *not* be redundant with ExitStack(), and hence could potentially counter the current rationale for not adding one.
Specifically, it relates to context managers like click.progressbar() that are designed to be used with an "as" clause:
with click.progressbar(iterable) as myiter:
for item in myiter:
...
At the moment, making that optional is a bit messy, since you need to do something like:
with click.progressbar(iterable) as myiter:
if not show_progress:
myiter = iterable # Don't use the special iterator
for item in myiter:
...
or:
with ExitStack() as stack:
if show_progress:
myiter = stack.enter_context(click.progressbar(iterable))
else:
myiter = iter(iterable)
for item in myiter:
...
or:
@contextmanager
def maybe_show_progress(iterable, show_progress)
if show_progress:
with click.progressbar(iterable) as myiter:
yield myiter
else:
yield iter(iterable)
with maybe_show_progress(iterable, show_progress) as myiter:
for item in myiter:
...
The problem is that there's no easy way to say "return *this* value from __enter__, but otherwise don't do anything special".
With a suitably defined NullContext, that last approach could instead look more like:
if show_progress:
ctx = click.progressbar(iterable)
else:
ctx = NullContext(iter(iterable))
with ctx as myiter:
for item in myiter:
... |
|
Date |
User |
Action |
Args |
2016-11-23 12:17:44 | ncoghlan | set | recipients:
+ ncoghlan, georg.brandl, rhettinger, blais, pitrou, vstinner, giampaolo.rodola, hniksic, eric.araujo, r.david.murray, michael.foord, daniel.urban, piotr.dobrogost, Alexander.Jones, DLitz, Martin Blais |
2016-11-23 12:17:44 | ncoghlan | set | messageid: <1479903464.32.0.715086350161.issue10049@psf.upfronthosting.co.za> |
2016-11-23 12:17:44 | ncoghlan | link | issue10049 messages |
2016-11-23 12:17:43 | ncoghlan | create | |
|