to close or not to close? 
Author Message
 to close or not to close?

Hi Gang,

Forgive me if this is a FAQ, 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?

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

=g2

_____________________________________________________________________


Publisher of dspGuru                           http://www.*-*-*.com/
Iowegian International Corporation             http://www.*-*-*.com/



Fri, 17 Jan 2003 03:00:00 GMT  
 to close or not to close?
Grant Griffin wrote in comp.lang.python:

Quote:
> Forgive me if this is a FAQ, 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?

Close it. Explicit is better than implicit, and you don't rely on the
__del__ method being called - for instance, in JPython the file wouldn't be
closed (afaik).

--

   This is no way to be
     Man ought to be free      -- Ted Bundy
       That man should be me



Fri, 17 Jan 2003 03:00:00 GMT  
 to close or not to close?
[Thomas Wouters]

Quote:

> > Forgive me if this is a FAQ, 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?

I came to consider it is a better form to _not_ close explicitely.  Cases
where explicit close is really useful are rather unusual, in my experience.
In which cases, an explicit `close' gets more meaningful, and less noisy.
And even then, I much prefer `file = None' than `close(file)', because the
former really represents my intent: I promise I will not use `file' anymore.
I like to think that closing a file is a system concern, not a user concern.

Quote:
> In current CPython it won't cause any problem to omit the close as long as
> you are certain the vrbl will go out of scope, but JPython and possibly
> other implementations of Python use true garbage collection (GC) rather
> than reference counting (RC).

This is true, and this is partly why I consider that CPython allows for
less cluttered coding in such areas.  I'm well prepared to revise my code
if I ever need to use JPython.  But until I do, I prefer clean and clear.

Quote:
> for x in [:256]: # or range(256) if you don't run experimental patches
>    open("tempfile.%d"%x)
> Will work just fine in CPython, having open at most 2 'tempfiles' at once
> (in an interactive session, that is, otherwise it has just 1 open.)

I do not understand how we could have two.  Since the result of `open'
is not saved, I presume the file will be closed immediately after being
opened, before executing the next instruction, or the next iteration.

Quote:
> But the same script under JPython, or a possible future CPython with true
> GC, will run out of filedescriptors (or more likely: the max number of
> open files) before the next GC run.

On this list, I got a kind of guarantee that future CPython will stick
with reference counting, possibly _complemented_ by more traditional mark
and sweep.  So, any current clean code will continue to work.

--
Fran?ois Pinard   http://www.iro.umontreal.ca/~pinard



Fri, 17 Jan 2003 03:00:00 GMT  
 to close or not to close?

Quote:

> Forgive me if this is a FAQ, 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?

If you care about portability of your code, and the code in question is
frequently executed inside the script (like in a rapid for-loop), you'd best
close it yourself. In current CPython it won't cause any problem to omit the
close as long as you are certain the vrbl will go out of scope, but JPython
and possibly other implementations of Python use true garbage collection
(GC) rather than reference counting (RC). GC is usually fired periodically,
or when system resources run low, and somehow not all GC's see
filedescriptors as system resources ;) So something like this:

for x in [:256]: # or range(256) if you don't run experimental patches
        open("tempfile.%d"%x)

Will work just fine in CPython, having open at most 2 'tempfiles' at once
(in an interactive session, that is, otherwise it has just 1 open.) But the
same script under JPython, or a possible future CPython with true GC, will
run out of filedescriptors (or more likely: the max number of open files)
before the next GC run.

(The above script is not that silly an example; I've actually used it, with
larger numbers, to create a large number of testfiles ;-) The example is
easily fixed, as the resulting isn't used. Just change it to
'open(..).close()'. It's just a tad trickier if you want to do
'open().read()' :-)

Of course, if you don't plan on running the code inside a busy for loop,
you'll hardly notice.

No-I-didn't-say-CPython-will-grow-true-GC!-ly y'rs,
--

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!



Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?

Quote:
> I came to consider it is a better form to _not_ close explicitely.  Cases
> where explicit close is really useful are rather unusual, in my
experience.
> In which cases, an explicit `close' gets more meaningful, and less noisy.
> And even then, I much prefer `file = None' than `close(file)', because the
> former really represents my intent: I promise I will not use `file'
anymore.
> I like to think that closing a file is a system concern, not a user

concern.

Why not 'del file'?  This should catch attempts to use 'file' earlier, and
should be more memory efficient.

--

Shareware action/role-playing games      -      http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor



Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?

Quote:
> Hi Gang,

> Forgive me if this is a FAQ, 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?

I think that depends on the programming culture one comes from.  People with
a C++ background are used to powerful idioms relying on destructors to free
all kinds of resources; people with a Java background are used to explicit
releasing (of non-memory resources), since finalize is not called reliably
(the
very explicit try/finally construct directly supports this style).  Other
languages
tend to fall into one or the other of these categories, too.

Python provides both reliably-called destructors (at least in CPython it
does;
the JPython or .NET dialects may work differently), _and_ try/finally, so
there
is really no 'pull' from the language itself towards one or the other idiom.

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

Yes, that's a plus for the omission.  OTOH, 'explicit is better than
implicit', so
you can find Scripture to support the other stance, too.  I think both
styles are
quite defensible -- one avoids clutter, the other makes it easier to port to
JPython (if ever that should be needed) and may make it clearer to someone
reading the code which resource is released where (a readability plus, to
be,
however, offset against the readability cost that more clutter entails).

Me, I tend to rely on destructors, but that just goes to show that my main
relevant background is in C++...:-).

Alex



Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?

Quote:

>I think that depends on the programming culture one comes from.
>People with a C++ background are used to powerful idioms
>relying on destructors to free all kinds of resources; people
>with a Java background are used to explicit releasing (of
>non-memory resources), since finalize is not called reliably
>(the very explicit try/finally construct directly supports this
>style).  Other languages tend to fall into one or the other of
>these categories, too.

>Python provides both reliably-called destructors (at least in
>CPython it does; the JPython or .NET dialects may work
>differently), _and_ try/finally, so there is really no 'pull'
>from the language itself towards one or the other idiom.

I think we're loosing one of the big advantages of Python if
users can't rely on objects "going away" when they're no longer
used and instead have to explicitly free() them.  The current
reference-counting problem that CPython has with circular
references is something I can live.  Having to explicitly
dispose of objects when I'm done with them would completely
ruin the "feel" of the language.

--
Grant Edwards                   grante             Yow!  Yow! We're going to
                                  at               a new disco!
                               visi.com            



Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?

    [snip]

Quote:
> >Python provides both reliably-called destructors (at least in
> >CPython it does; the JPython or .NET dialects may work
> >differently), _and_ try/finally, so there is really no 'pull'
> >from the language itself towards one or the other idiom.

> I think we're loosing one of the big advantages of Python if
> users can't rely on objects "going away" when they're no longer
> used and instead have to explicitly free() them.  The current
> reference-counting problem that CPython has with circular
> references is something I can live.  Having to explicitly
> dispose of objects when I'm done with them would completely
> ruin the "feel" of the language.

The need to call an explicit .close(), or whatever, really only
applies to objects which are encapsulating/owning a scarce
resource -- an open file, a database connection, something
like that.  As I said, I like the automatic-destruction-idiom,
myself, and I dearly hope it's maintained (perhaps only when
explicitly requested; I do realize reference-counting to obtain
immediate reliable destruction is a costly approach if/when
one has good, "serious" GC going on anyway!) wherever it's
feasible to maintain it.  That much being said, I think your
worry on the subject might perhaps be excessive; the try/
finally idiom is in Python for a purpose (presumably, to offer
support to programmers that don't _want_ to have to wrap
every costly-resource into a class, with its release in the
destructor, but would rather be more explicit about those few
instances of costly-resource-acquisition-and-release).

I'd rather be able to wrap costly resources in specially
designed classes (e.g., ones inheriting from a hypothetical
sys.Release_ASAP class...?), as a compromise between
every class being release-ASAP and none being so, but, if
such a compromise should be technically unfeasible, I'll live
with garbage-collection-only, and try/finally, if and when those
are the prices to be paid for substantial benefits (increases
in performance, and/or coexistence in interesting environments,
such as JVM or the .Net Framework...).

Alex



Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?

...

| I think we're loosing one of the big advantages of Python if
| users can't rely on objects "going away" when they're no longer
| used and instead have to explicitly free() them.  The current
| reference-counting problem that CPython has with circular
| references is something I can live.  Having to explicitly
| dispose of objects when I'm done with them would completely
| ruin the "feel" of the language.

I would (and have) put it more strongly than "feel".  It makes
very little difference in most programs, I guess, but there are
times when this is a huge feature.  Luckily there seem to be some
ideas about garbage collection as an accessory that would solve
cycles but otherwise preserve normal reference counting behavior.
If we're losing it, it's news to me.




Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?
[Tim Peters, on Mon, 31 Jul 2000]
:: So the "cover your butt" answer is "close it!".

OK, but presumably you (Tim) don't do that in every instance, right? On
the assumption that your heuristics are superior to those of most of us
on this NG, it would be instructive if you would essay to outline the
rough thinking process (or the "m{*filter*}struggle") you might typically go
through to decide whether or not to close manually.



Sat, 18 Jan 2003 03:00:00 GMT  
 to close or not to close?


Quote:

>Grant Griffin wrote in comp.lang.python:
>> Forgive me if this is a FAQ, 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?

>Close it. Explicit is better than implicit, and you don't rely on the
>__del__ method being called - for instance, in JPython the file wouldn't be
>closed (afaik).

Thanks, Remco (and to others)--that helps.

Coincidentally, when reading about Perl6 today, I ran onto this at
http://www.perl.com/pub/2000/07/perl6.html:

"Every few months, someone suggests replacing Perl's garbage collector with a
more modern one, but there are always objections from people who have written
code that assumes that the garbage collector will always be reference-count
based and that it can control when objects will be destructed."

(explict-is-better-than-implicit-even-in-perl-<wink>)-ly y'rs,

=g2

_____________________________________________________________________


Publisher of dspGuru                           http://www.dspguru.com
Iowegian International Corporation            http://www.iowegian.com



Sat, 18 Jan 2003 03:00:00 GMT  
 
 [ 11 post ] 

 Relevant Pages 

1. Closed file not really closed

2. mdi app not closing down, some threads just won't close #2

3. Device file not closing on close command

4. CW55PE release H when I close a wizard generated application the IDE closes as well

5. tcl-dp confuses expect's close call with builtin close

6. Dangling Closing Parentheses vs. Stacked Closing Parentheses

7. close of an arbitrary stream may close *terminal-io*

8. Menubar not refreshed when closing a modal dialog

9. SpriteSurace not closing in RB3

10. Tray Application not closing on windows shutdown

11. "you have not called FileManager.Close()"

12. Close buttons not working ????

 

 
Powered by phpBB® Forum Software