kgf3JfUtW
kgf3JfUtW

Reputation: 14918

Return value of __exit__

I understand that


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,

Upvotes: 38

Views: 15613

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

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?).

Upvotes: 40

Related Questions