[Python-ideas] if <expression> as <variable>
Chris Angelico
rosuav at gmail.com
Thu Sep 7 15:48:29 EDT 2017
On Fri, Sep 8, 2017 at 5:40 AM, Philipp A. <flying-sheep at 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
More information about the Python-ideas
mailing list