Allowing ref counting to close file items bad style?

Paul Rubin http
Wed Aug 30 03:47:57 EDT 2006


"sjdevnull at yahoo.com" <sjdevnull at yahoo.com> writes:
> Sure.  But most Java GCs are pretty reasonable and for typical code
> will run periodically (what I call the not-horribly-distant future).

If your system allows max 100 files open and you're using 98 of them,
then "horribly distant future" can be awfully close by.

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

Ref counting is a rather primitive GC technique and implementations
shouldn't be stuck having to use it.

> It's obvious to the reader that in code like:
> 
> def myFunc(filename):
>   f = open(filename, 'r')
>   for line in f:
>       # do something not using f

That's not obvious except by recognizing the idiom and knowing the
special semantics of files.  Otherwise, look at

  def myOtherFunc(x):
     a = SomeClass(x)  # make an instance of some class
     b = a.foo()
     # do something with b

One can't say for sure that 'a' can be destructed when the above
function finishes.  Maybe a.foo() saved a copy of its 'self' argument
somewhere.  It's the same thing with your file example: "for line in f"
calls f's iter method and them repeatedly calls f's next method.
Those methods could have side effects that save f somewhere.

> Having f destructed at least when the function returns makes for more
> readable code and fewer mistakes.  CPython's refcounting behaves very
> nicely in this regard,

The ref counting only works if it applies to all the lower scopes and
not just the local scope.  That means you can't use any other type of GC.



More information about the Python-list mailing list