Python exceptions and refcounts
Kragen Sitaker
kragen at pobox.com
Wed Jan 23 04:36:38 EST 2002
Duncan Booth <duncan at NOSPAMrcp.co.uk> writes:
> If you need to be sure that references to an object are removed even if the
> function throws an exception then wrap the body of the function in a
> try:finally: block and del the object in the finally suite. Also remember
> always to close things like files and not depend on the variable going out
> of scope to do the tidying up.
And, by the way, try:finally: is an excellent way to do things like
close files.
Lately I've been doing this kind of thing; instead of writing:
def getnext(self):
tmp = self.seq[self.ii]
self.ii = self.ii + 1
return tmp
I do this:
def getnext(self):
try: return self.seq[self.ii]
finally: self.ii = self.ii + 1
In the absence of exceptions, both will do the same thing.
I'm not sure this is an actual improvement; I think I may be
succumbing to the Premature Optimization Demon, in its worst form: the
tendency to shorten one's code.
More information about the Python-list
mailing list