context managers inline?
Steven D'Aprano
steve at pearwood.info
Thu Mar 10 23:35:18 EST 2016
On Fri, 11 Mar 2016 05:33 am, Neal Becker wrote:
> Is there a way to ensure resource cleanup with a construct such as:
>
> x = load (open ('my file', 'rb))
>
> Is there a way to ensure this file gets closed?
Depends on what you mean by "ensure". Have load() call the file's close
method may be good enough.
If you want a better guarantee, you need either a with block:
with open(...) as f:
...
or a finally block:
try:
...
finally:
...
There is no expression-based version of these.
--
Steven
More information about the Python-list
mailing list