Sadly it’s hard to create a context manager that skips its body like this:

with unpack(computation()) as result:


You can do it with some hackery like described here:

class unpack:
    def __init__(self, pred):
        self.pred = pred

    def __enter__(self):
        if self.pred:
            return self.pred
        # else skip the with block’s body
        sys.settrace(lambda *args, **kw: None)
        frame = inspect.currentframe(1)
        frame.f_trace = self.trace

    def trace(self, frame, event, arg):

    def __exit__(self, type, value, traceback):
        return True  # suppress the exception

Steven D'Aprano <> 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()
if x:

> I would offer that 'with' [sh|c]ould be used:
> with test() as x:
>    handle_truthy(x)
> else:
>    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: