473,396 Members | 1,760 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,396 software developers and data experts.

Uncatchable AttributeError, shelve raises exceptions in __del__

Last week I encountered an AttributeError in my unit tests that I
wasn'table to catch with an "except AttributeError" statement.

The problem stemmed from a class that raised an error inside
__init__and defined a __del__ method to clean up resources. I then
discovered asimilar problem in the shelve module. This led me to two
importantdiscoveries:

1. Attributes defined in __init__ after an error is raised will not be
apart of the "self" passed to __del__. On reflection, this seems
quiteobvious, but it is easy to have this bite you because it is
"morePythonic", I think, to define class attributes inside __init__ on
anas-needed basis. In less dynamic languages, say Java, one defines
allclass attributes at the class level, which is allowed in Python,
and soall class attributes are defined when the constructor is called.

2. As documented(http://www.python.org/doc/current/re...mization.html),
If anexception is raised in __del__, a message is printed to stderr
and it isignored. This means that such an exception cannot be caught
with"except"! This can be a pain if such an error is raised in a
modulethat isn't your code.

As an aside, why isn't __del__ documentation in the index with the
other"_ (underscore)" stuff?
See:http://www.python.org/doc/current/lib/genindex.html

Here's an example that shows how the location of attribute
definitionsinside __init__ can lead to AttributeErrors in __del__ (and
henceuncatchable errors):

class AttributeErrorRaiser:
def __init__(self, be_bad=True):
self.earlyAttribute = "early"
if be_bad:
raise SomeError()
self.lateAttribute = "late"
def __del__(self):
print self.earlyAttribute
print self.lateAttribute

class SomeError(Exception):
def __init__(self, args=None):
self.args = args
try: ... aer = AttributeErrorRaiser()
... except SomeError:
... print "Caught SomeError"
...
Caught SomeError
early
Exception exceptions.AttributeError: "AttributeErrorRaiser
instance has no attribute 'lateAttribute'" in <bound method
AttributeErrorRaiser.__del__ of <trytocatchme.AttributeErrorRaiser
instance at 0x402e9d0c>> ignored

And here is the same programming error in the shelve module. Assume
that 'notashelf.txt' is an existing plain text file:

import shelve
import anydbm

class ShowShelfBadness:
def __init__(self):
try:
self.shelf = shelve.open('notashelf.txt')
except anydbm.error:
print "caught a shelve related error"
ssb = ShowShelfBadness()

caught a shelve related error
Exception exceptions.AttributeError: "DbfilenameShelf instance has
no attribute 'writeback'" in ignored

The workaround that I found was to use the whichdb module to test for
a valid shelf-type file, if the file exists, before opening with
shelve, but I still don't like the fact that shelve.open raises an
"uncatchable" error when you give it a bad file.

Questions:

Does anyone have suggestions for "best practice" w.r.t. defining
attributes in __init__ or at the class level?

Thoughts on workarounds for the behavior shown in the shelve module?
Thanks for listening.
Jul 18 '05 #1
0 2442

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

Similar topics

6
by: Rami A. Kishek | last post by:
Hi - this mysterious behavior with shelve is just about to kill me. I hope someone here can shed some light. First of all, I have this piece of code which uses shelve to save instances of some...
6
by: Rune | last post by:
Hi, I've written a very simple 'kill-server' to help me shut down processes through Telnet or HTTP. The kill-server is a function and is launched as a thread. I use the module socket.py on Python...
0
by: Erlend Fuglum | last post by:
I have tried and tried, but cannot figure out the source of the following error: AttributeError: 'module' object has no attribute 'menyHMTL' __doc__ = 'Attribute not found.' __getitem__ =...
16
by: David Turner | last post by:
Hi all I noticed something interesting while testing some RAII concepts ported from C++ in Python. I haven't managed to find any information about it on the web, hence this post. The problem...
0
by: PiedmontBiz | last post by:
I am finishing up a simple survey for a web site. I am creating a server-side data base using the shelve module. I am a relative python newcomer. I began with anydbm, but found that shelve uses...
7
by: cs | last post by:
We have some code that walks the process tree on windows xp. It uses the process class in system diagnostic as well as some dllimport calls to kernel32.dll and ntdll.dll We also have some code...
6
by: aomighty | last post by:
I wanted to write the following code: import shelve try: db = shelve.open(file, "r") except SomeError: print "Oh no, db not found" Only, I'm not sure what SomeError should be. I tried...
7
by: erikcw | last post by:
Hi, I'm trying to build a SQL string sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid, ag, self.data) It raises this error: AttributeError: 'tuple' object has no...
4
by: Nikhil | last post by:
I have recently written a small module. When I import the module, I always get the error only when I do -- Traceback (most recent call last): File "<stdin>", line 1, in <module>
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.