Return Value __exit__

I understand that

  • __enter__ and __exit__ are used to implement the context manager.

  • If an exception occurs in the with statement, the type of exception, value, and trace are passed to the __exit__ method.

  • __exit__ can handle the exception:

    • Return True : The exception is handled correctly.
    • Returning everything else: the with statement throws an exception

I came across the following __exit__ method. Is redundant expression redundant?

 def __exit__(self, type, value, traceback): self.close() return type == None 

as it seems to me that

  • If an exception does not occur, type will naturally be None , so __exit__ returns true. Nothing arises.
  • If an exception occurs, type set to the actual type of the exception, so __exit__ returns false. An exception is thrown as is.
+5
source share
1 answer

Yes, this return statement is redundant. Only when type not None is return.

From the object.__exit__() documentation :

If an exception is thrown and the method wants to suppress the exception (i.e., prevent its propagation), it should return the true value. Otherwise, the exception will usually be processed after exiting this method.

Note that true value will suppress the exception; therefore 1 or "Handled!" will also work, not just True .

Removing this return line will return None , and the functionality will remain unchanged. However, readability will be improved because this return type == None just confused at several levels (why not use type is None , for example?).

+7
source

All Articles