472,358 Members | 1,899 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,358 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

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?

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
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):
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.


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 2339

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

Similar topics

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...
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...
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__ =...
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...
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...
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...
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...
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...
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>
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

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.