Context manager for files vs garbage collection

Sebastian "lunar" Wiesner basti.wiesner at gmx.net
Tue Jun 17 13:24:06 EDT 2008


Floris Bruynooghe <floris.bruynooghe at gmail.com>:

> 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

Using this code inside a jthon web application might hit the resource limits
of the underlying operating system.

While CPython has a fairly deterministic garbage collector, the JVM gc is
non-deterministic, especially inside the server vm.  It keeps objects
around for quite a long time and only frees them, if available memory runs
low or the application is idle.  Since file objects don't consume much
memory, they might be hanging around for quite some time still claiming
resources,  which are a rare thing on many restricted server environments.

Relying on garbage collection on Python means relying on a non-portable
implementation detail.

-- 
Freedom is always the freedom of dissenters.
                                      (Rosa Luxemburg)



More information about the Python-list mailing list