473,395 Members | 1,701 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

reference counting and file objects

def uselessHash(filename):
fp= open(filename)
hash= 0
for line in fp:
hash ^= hash(line.strip())
fp.close() # do I need this or is fp closed by ref count?
return hash

Consider the function above. Do I need the fp.close(), or will the
file be closed automatically when fp goes out of scope and its
reference count drops to zero?

If so, there's really no point in calling .close() in situations like
this where the function completes in a relatively short time,, and if
not, I should probably be using try-finally. That's my thinking... or
the thinking of the coworker who was arguing with me.
Jul 19 '05 #1
6 1714
John Reese <jt*@ofb.net> writes:
Consider the function above. Do I need the fp.close(), or will the
file be closed automatically when fp goes out of scope and its
reference count drops to zero?


In CPython, fp gets closed when it leaves scope. In other
implementations you may need try-finally. There's been occasional
discussion of possible new Python control blocks to make this easier.
Jul 19 '05 #2
Paul Rubin wrote:
Consider the function above. Do I need the fp.close(), or will the
file be closed automatically when fp goes out of scope and its
reference count drops to zero?


In CPython, fp gets closed when it leaves scope.


One issue is that when the function terminates through an exception,
the file stays open as long as the traceback is available, which
exists until the next exception is raised (and thus replaces this
traceback).

If the function terminates normally (i.e. through return), it is
as you say.

Regards,
Martin
Jul 19 '05 #3

Martin v. Löwis wrote:
Paul Rubin wrote:
Consider the function above. Do I need the fp.close(), or will the
file be closed automatically when fp goes out of scope and its
reference count drops to zero?


In CPython, fp gets closed when it leaves scope.


One issue is that when the function terminates through an exception,
the file stays open as long as the traceback is available, which
exists until the next exception is raised (and thus replaces this
traceback).

If the function terminates normally (i.e. through return), it is
as you say.

Regards,
Martin


Does the idiom:

lines = file("myfile","r").readlines()

have any better guarantee of being closed automatically?

Peter

Jul 19 '05 #4
Peter wrote:
Does the idiom:

lines = file("myfile","r").readlines()

have any better guarantee of being closed automatically?


Yes. The file object only lives on the evaluation stack,
and that is discarded in any case when the function terminates
(whether through a return or through an exception). In
addition, the object is released as soon as readlines
returns.

Regards,
Martin
Jul 19 '05 #5
"Martin v. Löwis" <ma****@v.loewis.de> writes:
lines = file("myfile","r").readlines()

have any better guarantee of being closed automatically?


Yes. The file object only lives on the evaluation stack,
and that is discarded in any case when the function terminates
(whether through a return or through an exception). In
addition, the object is released as soon as readlines
returns.


It's released even if the exception is raised inside readlines?
Jul 19 '05 #6
Paul Rubin wrote:
lines = file("myfile","r").readlines()
It's released even if the exception is raised inside readlines?


I think so, but only because readlines is a builtin function.
If it wasn't, there would be a stack frame for readlines, which
would have "self" as a local variable.

As readlines is builtin, it will not make it into the traceback.
So the reference to the file would be only on the evaluation
stack, at first, but that then gets copied into the argument
tuple. The argument tuple, in turn, is released in the process
of unwinding (again, it wouldn't if readlines wasn't builtin).

I might be wrong, but I think the following trace shows that
this is what happens:
class F: .... def __del__(self):print "released"
.... len(F()) released
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: F instance has no attribute '__len__'

Compare this to a Python function:
def len2(o): raise Exception .... len2(F()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in len2
Exception raise ""

released
Traceback (most recent call last):
File "<stdin>", line 1, in ?

However, this analysis also shows that it is quite delicate
to rely on this pattern.

Regards,
Martin
Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Elbert Lev | last post by:
Please correct me if I'm wrong. Python (as I understand) uses reference counting to determine when to delete the object. As soon as the object goes out of the scope it is deleted. Python does...
1
by: ash | last post by:
hi does anyone has any experience with flyweight pattern with refernce counting i want to share objects between multiple clients and want to delete the object from shared pool when the last...
1
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that I don't understand completely. It says "A garbarage...
1
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that I don't understand completely. It says "A garbarage...
7
by: Fred Hedges | last post by:
I'm wondering if a tool exists that will integrate with the VS 2005 debugger, such that when I set a breakpoint I can inspect a reference and see how many other references exist to that object. ...
3
by: Ole Nielsby | last post by:
I need to implement reference counting in a class hierarch, in a thread safe manner. (The classes are umanaged but I might want to compile them with the /clr option.) Some of the objects - atoms...
1
by: oec.deepak | last post by:
Hi Cn any one telll me what is Reference counting in C++.
8
by: mdoxdo | last post by:
Hi all, I was wondering if there is a way to get the number of references an objects have (ie, other objects reference that object)? I know that .Net GC uses a different mechanism than the...
5
by: colin | last post by:
Hi, I need to cache various resource objects such as images for example, wich might be referenced from multiple objects (wich could be considered documents for ease of discusion) and the idea is...
275
by: Astley Le Jasper | last post by:
Sorry for the numpty question ... How do you find the reference name of an object? So if i have this bob = modulename.objectname() how do i find that the name is 'bob'
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.