On Fri, Sep 8, 2017 at 5:40 AM, Philipp A. <flying-sh...@web.de> wrote:
> sorry, it’s a bit more difficult. this works:
> https://gist.github.com/flying-sheep/86dfcc1bdd71a33fa3483b83e254084c

If this can be made to work - even hackily - can it be added into
contextlib.contextmanager (or technically its helper class)?
Currently, its __enter__ looks like this:

    def __enter__(self):
        try:
            return next(self.gen)
        except StopIteration:
            raise RuntimeError("generator didn't yield") from None

If that raise were replaced with the hackiness of skipping the body,
we could wrap everything up nicely:

@contextlib.contextmanager
def iff(thing):
    if thing: yield thing
    # otherwise don't yield

for i in range(1, 11):
    with iff(random.randrange(3)) as val:
        print(i, val) # won't print any zeroes

ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to