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__
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With