3

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__
5
  • what do you want to do? what is the expected behaviour? do you want to basically have giving a code example doesn't describe what you want to achieve. Commented Jan 13, 2016 at 20:45
  • I think he wants the resulting code behave like the first example. Can't think of a different interpretation TBH Commented Jan 13, 2016 at 20:47
  • What are you actually trying to do? Commented Jan 13, 2016 at 20:48
  • 1
    @MarkusUnterwaditzer: It might be hard to understand because it doesn't make sense to do that. You shouldn't attempt to replicate a try/except block with with. Commented Jan 13, 2016 at 20:49
  • using the with statement is one option the other one is to decorate the function. if you want this at function scope it might be cleaner: python-3-patterns-idioms-test.readthedocs.org/en/latest/… on a side note: syntax error is also an exception that looks dangerous in python. Commented Jan 13, 2016 at 20:50

1 Answer 1

10

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")
Sign up to request clarification or add additional context in comments.

3 Comments

potentially precisely what the OP wants.
Oh snap, that was fast. Thank you sir.
Effectively the contextmanager adds the missing .__exit__ attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.