to close or not to close?

Tim Peters tim_one at email.msn.com
Tue Aug 1 02:16:39 EDT 2000


[Grant Griffin]
> Forgive me if this is a FAQ,

Not yet, but it's likely to become one <wink -- but see below>.

> but is it considered good Python form to close a file whose
> variable is just about to go out of scope (and thus be
> automatically closed)?  Or should one just omit that?

In part the question seems based on a misunderstanding (perhaps
C++-inspired), and that's worth explaining:  a Python vrbl going out of
scope has nothing direct to do with whether the object it names is
destructed.  Python has no "auto"-- or block --vrbls!  "Going out of scope"
in CPython just means that the object's refcount gets decremented.  The
object may or may not become dead as a result of that.

So the file certainly won't be closed automatically if references to it
remain.  If the local name was the last reference to it, the language
(according to the Reference Manual) doesn't define when the object will be
destructed -- or even guarantee that it will ever be destructed!

So the "cover your butt" answer is "close it!".  CPython happens to use
reference-counting to reclaim dead objects, so in CPython destruction
happens (in the absence of pathologies, like cycles) immediately upon the
loss of the last reference.  So a lot of CPython code relies on this,
wittingly or not -- even modules in the source distribution implicitly rely
on it (to Guido's recent chagrin <wink>).

But, so far, CPython is the only Python implementation that enjoys this
behavior.  JPython does not, John Skaller's Vyper does not, and AFAIK the
MS-based Python .NET will not.

> tempted-to-omit-needless-code-ly y'rs,

it-is-indeed-a-moral-struggle-ly y'rs  - tim






More information about the Python-list mailing list