Newbie question 2

Peter Otten __peter__ at web.de
Sun Nov 9 11:30:27 CET 2003


Rob wrote:

>> Traceback (most recent call last):
>>   File "C:\Python23\phone.py", line 118, in -toplevel-
>>     dele(dn,dp)
>>   File "C:\Python23\phone.py", line 70, in dele
>>     except (DBNotFoundError, NameError):
>> NameError: global name 'DBNotFoundError' is not defined

You have edited the code since you generated the traceback. 
Try to keep posted code as small as you can and make sure it is in sync with
the posted output.

> def dele(name,ptype):
>         e = shelve.open('C:/phonedata')
>         print e
>         f = name + ':' + ptype
>         print
>         try:
>             del e[str(f)]
>             e.close()
>             print 'Entry deleted.'
>         except (NameError):
>             print 'No Entries with '+ptype+' exist!'

(I'll confine my comments to the dele() function)

The error thrown when you try to delete a shelve entry with a non-existent
key is _bsddb.DBNotFoundError, so you probably want to catch that.
You want the shelve to be always closed, so put the e.close() call into a
finally statement.
The error message in the except clause is misleading as there *may* exist
entries with the shown ptype part of the key.
Don't duplicate constants, i. e. the filename.
Putting it all together:

import shelve, _bsddb

filename = 'C:/phonedata'

def dele(name, ptype):
    key = name + ':' + ptype
    db = shelve.open(filename)
    try:
        try:
            del db[key]
            print 'Entry', key, 'deleted.'
        except _bsddb.DBNotFoundError:
            print 'No Entries with', key, 'exist!'
    finally:
        db.close()

Peter





More information about the Python-list mailing list