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:- Returning
True
: the exception is gracefully handled. - Returning anything else: the
with
statement raises the exception
- Returning
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 beNone
, 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.