Context manager for files vs garbage collection
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Mon Jun 16 09:24:45 EDT 2008
Floris Bruynooghe a écrit :
> Hi
>
> I was wondering when it was worthwil to use context managers for
> file. Consider this example:
>
> def foo():
> t = False
> for line in file('/tmp/foo'):
> if line.startswith('bar'):
> t = True
> break
> return t
>
> What would the benefit of using a context manager be here, if any?
> E.g.:
>
> def foo():
> t = False
> with file('/tmp/foo') as f:
> for line in f:
> if line.startswith('bar'):
> t = True
> break
> return t
>
> Personally I can't really see why the second case would be much
> better, I've got used to just relying on the garbage collector... :-)
IIRC (please someone correct me if I'm wrong), proper release of file
resources as soon as the file object gets out of scope is not garanteed
in the language spec and is implementation dependant.
More information about the Python-list
mailing list