Consider the following:
with open(path, mode) as f:
return [line for line in f if condition]
Will the file be closed properly, or does using return somehow bypass the context manager?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, it acts like the
finallyblock after atryblock, i.e. it always executes (unless the python process terminates in an unusual way of course).It is also mentioned in one of the examples of PEP-343 which is the specification for the
withstatement:Something worth mentioning is however, that you cannot easily catch exceptions thrown by the
open()call without putting the wholewithblock inside atry..exceptblock which is usually not what one wants.