Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to wrap this in a Python "with" statement?

Is it possible to use it to achieve the following? (using the "with" keyword or not)

Before:

try:
    raise Exception("hello")
except Exception as e:
    print "GOT IT"

Desired effect:

def safety():
    try:
        yield
    except Exception as e:
        print "GOT IT"

with safety():
    raise Exception("hello")

It just makes the code so much cleaner. Currently running the second snippet gives the error:

Traceback (most recent call last):
  File "testing.py", line 25, in <module>
    with safety():
AttributeError: __exit__
like image 634
ed928 Avatar asked Apr 26 '26 18:04

ed928


1 Answers

You were so close!

from contextlib import contextmanager

@contextmanager
def safety():
    try:
        yield
    except Exception as e:
        print "GOT IT"

with safety():
    raise Exception("hello")
like image 64
Markus Unterwaditzer Avatar answered Apr 29 '26 06:04

Markus Unterwaditzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!