Somehow my brain seems to think there's a reason not to return inside a with statement, so rather then doing this:
def foo(): with ctx_manager: return bar()
I always do:
def foo(): with ctx_manager: result = bar() return result
No idea why nor where I think to have heard/read this. Searching for this brings up absolutely no rationale. So if you know why this is so, or know that the first version is perfectly fine, please enlighten me!
Seems it's only relevant if you're reading a file using the with statement. This seems to have come from the python documentation itself:
The last version is not very good either — due to implementation details, the file would not be closed when an exception is raised until the handler finishes, and perhaps not at all in non-C implementations (e.g., Jython).
def get_status(file): with open(file) as fp: return fp.readline()
Sadly it doesn't say what the implementation details are nor how to do this correctly. I can have several more or less educated guesses at why and which way to do this better. But I'd love to get a more detailed description of what happens in the implementations when doing this, because the worst-case way of interpreting that example is that using
file() as a context manager is completely useless. Which I would hate.