Allowing ref counting to close file items bad style?

Paul Rubin http
Wed Aug 30 00:10:12 EDT 2006


"sjdevnull at yahoo.com" <sjdevnull at yahoo.com> writes:
> I disagree, somewhat.  No, you shouldn't count on the "ref count" per
> se going to 0.  And you shouldn't count on the file object being GC'd
> _immediately_ after the last reference is destroyed. You should be able
> to rely on it being GC'd at some point in the not-horribly-distant
> future, though.

Is there something in the language specification that says I should be
able to rely on something like that?  In Jython, for example, I think
GC is handled totally by the underlying JVM and therefore totally up
to the Java implementation.

> Doing an explicit .close() is not normally useful and muddies the code
> (and introduces more lines for potential bugs to infest).

Yes, the "with" statement is the right way to do it.

> And yes, I know that the language spec technically allows for no GC at
> all--it's a QOI issue, not a spec issue, but any implementation that

QOI?

> didn't GC would be useless as a general Python platform (perhaps useful

GC's typically track memory allocation but not file handle allocation.
If you're opening a lot of files, you could run out of fd's before the
GC ever runs.

> (And personally I think the benefits to programmers of guaranteeing
> ref-counting semantics would outweigh the additional headaches for
> Jython and other alternative implementations).

Yes, "with" (doing an implicit close guaranteed to happen at the right
time) takes care of it properly.



More information about the Python-list mailing list