[Python-ideas] if <expression> as <variable>

Philipp A. flying-sheep at web.de
Thu Sep 7 15:21:40 EDT 2017


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/247482

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):
        raise

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

Steven D'Aprano <steve at pearwood.info> 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:
>     do_stuff()
>
>
> > 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:
>    do_stuff
>
> 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.
>
>
> --
> Steve
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170907/f237df4b/attachment-0001.html>


More information about the Python-ideas mailing list