Context manager for files vs garbage collection

Floris Bruynooghe floris.bruynooghe at gmail.com
Mon Jun 16 06:48:29 EDT 2008


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... :-)
But what is the use case of a file as a context manager then?  Is it
only useful if your file object is large and will stay in scope for a
long time?

Regards
Floris



More information about the Python-list mailing list