Sadly it’s hard to create a context manager that skips its body like this:with unpack(computation()) as result:
do_something_with_result(result)You can do it with some hackery like described here: https://stackoverflow.com/a/12594789/247482class unpack:def __init__(self, pred):self.pred = preddef __enter__(self):if self.pred:return self.pred# else skip the with block’s bodysys.settrace(lambda *args, **kw: None)frame = inspect.currentframe(1)frame.f_trace = self.tracedef trace(self, frame, event, arg):raisedef __exit__(self, type, value, traceback):return True # suppress the exceptionSteven D'Aprano <firstname.lastname@example.org> schrieb am Do., 7. Sep. 2017 um 18:26 Uhr:On Thu, Sep 07, 2017 at 04:36:40PM +0200, Jason H wrote:
> I also often wonder why we are left doing an assignment and test. You have two options:
> 1. assign to a variable then test and use
> 2. repeat the function call
Personally, I don't see what's wrong with the "assign then test" idiom.
x = something()
> I would offer that 'with' [sh|c]ould be used:
> with test() as x:
> handle_falsey() # do we provide x here too? Because None vs False?
This would cause confusing errors and mysterious behaviour, depending on
whether the test() object was a context manager or not. Which should
take priority? If you see:
with spam() as x:
is that a context manager with block (like "with open(...) as f") or
your boolean if test in disguise?
Having "with" sometimes be a disguised "if" and sometimes a regular
"with" will make it really, really hard to reason about code.
Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/