0

Here is a sample code :

class test :
    def __init__(self, text) :
        self.text = text
    def __enter__(self) :
        print("some text" + self.text)
    def __exit__(self, *args) :
        self.text = None
        print(args)
        return True

with test("hello world") :
    pass
with test(12) :
    pass

I use string concatenation in the __enter__ function so that if the text argument is an int, a TypeError will occur (but should not be thrown because of the with statement)

From python docs

If an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be.

If the suite was exited due to an exception, and the return value from the exit() method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the with statement.

So here __exit__ return True so why when I run this sample code, an error is thrown ?

Thank you for helping

ScarySneer
  • 199
  • 3
  • 9

1 Answers1

0

The second example in your code never calls the __exit__ method because the __enter__ method raises an error. All of the error handling that gets passed to __exit__ happens in the code block after __enter__ completes.

James
  • 32,991
  • 4
  • 47
  • 70