33

I understand that

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

  • if an exception occurs in a with statement, the exception's type, value and traceback are passed to the __exit__ method.

  • __exit__ can handle the exception:

    1. Returning True: the exception is gracefully handled.
    2. Returning anything else: the with statement raises the exception

I came across the following __exit__ method. Is the return statement redundant?

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

since it seems to me that,

  • If no exception occurred, type will naturally be None, so __exit__ returns true. Nothing is raised.
  • If an exception did occur, type is set to the actual exception type, so __exit__ returns false. The exception is raised as is.
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
kgf3JfUtW
  • 13,702
  • 10
  • 57
  • 80
  • 6
    That's a confusing `return` statement on more than one level. Never use `== None` when you can use `is None` instead. But yes, just remove that `return` line altogether for all that it is worth. – Martijn Pieters May 12 '17 at 21:07
  • 4
    It's also confusing when you name method argument `type`. Because `type` is already build-in keyword. it's better to use `exc_type` as it don't confuse and not shadows build-in keyword. – vishes_shell May 12 '17 at 22:47

1 Answers1

37

Yes, that return statement is redundant. Only when type is not None does the return value matter.

From the object.__exit__() documentation:

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

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

Removing that return line would result in None being returned instead, and the functionality would remain unchanged. Readability would be improved however, because that return type == None statement is just confusing on multiple levels (why not use type is None for example?).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343