gc question
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Mon Mar 10 01:14:00 EDT 2008
On 9 mar, 15:37, I V <ivle... at gmail.com> wrote:
> On Sun, 09 Mar 2008 01:57:38 -0800, Vince wrote:
> > Well, that suits me. The most unnatural thing about Python was adapting
> > to the idea of just letting unreleased resources go jogging off
> > wherever. :)
>
> Yes, that's a bad habit that garbage collection can encourage. GC is good
> for managing memory, but not good for managing other resources, so if an
> object holds some other resource, it's important to make sure the
> resource is released in a timely fashion rather than relying on the
> finalizer (the __del__ function).
>
> Although, you still don't need f.close, with the new with statement:
>
> with open('myfile') as f:
> string = f.readline()
> # f.close() gets called automatically here, without waiting for
> # garbage collection.
Just for completeness, on earlier Python versions, the way to ensure
that resources are always released is using try/finally:
f = open(...)
try:
...work with file...
finally:
f.close()
--
Gabriel Genellina
More information about the Python-list
mailing list