Block-structured resource handling via decorators

Paul Rubin http
Fri Jul 29 20:34:54 EDT 2005


Mike Meyer <mwm at mired.org> writes:
> > When handling resources in Python, where the scope of the resource is
> > known, there seem to be two schools of thought:
> > (1) Explicit: ...
> > (2) Implicit: let the GC handle it.
> 
> The only cases I see the first school of thought is when the resource
> in question is "scarce" in some way. For example, most OS's place a
> limit on the number of open files a process can have, some rather
> tight. CPython's garbage collector will close an open file when it
> leaves scope. Jython's GC will close it when the file is collected,
> but you have no idea of when that will be, and an "open" failing won't
> trigger a GC. So in this case, the first form is less likely to fail
> unexpectedly.

I thought there was a Zen thing somewhere saying that Python is not
Perl.  One of Perl's silliest tenets is that the implementation
defines the language.  There are already 4 different Python
implementations (CPython, Jython, Pypy, IronPython) and probably more
on the way.  We should take the view that the manual, not the
implementation, defines the language.

The manual doesn't specify anything about reference counting or GC
happening as soon as something goes out of scope.  That is a GOOD
thing since requiring CPython-like behavior would eliminate many good
GC techniques, including some that are both more efficient and easier
for extension writers to deal with.  Since reference counting is not
in the manual, it is not part of the language, it's subject to change
at any time in any implementation, and non-throwaway Python apps
should not depend on it.  

On the other hand, the try/finally explicit release is cumbersome and
non-tasty.  

Therefore, the correct solution is a language extension along the
lines of PEP 343.  I haven't studied PEP 343 specifically enough to
say that I think every detail of it is the right thing, but at least
it is the right idea.




More information about the Python-list mailing list