[Tutor] String Encoding problem

Martin Walsh mwalsh at mwalsh.org
Mon Apr 20 22:12:56 CEST 2009

Matt wrote:
> Hey everyone,
> I'm hoping someone here can help me solve an odd problem (bug?). I'm
> having trouble with string encoding, object deletion, and the xml.etree
> library. If this isn't the right list to be posting this question,
> please let me know. I'm new to Python and don't know of any other "help
> me" Python mailing lists. I have tried debugging this ad-infinitem.
> Anyway, at the bottom of this e-mail you will find the code of a python
> file. This is a gross over-simplification of my code, with little
> exception handling so that the errors are obvious.
> Running this interactively, if you finish off with 'del db', it exits
> fine and creates a skeleton xml file called 'db.xml' with text '<root
> />'. However, if you instead CTRL-D, it throws at exception while
> quitting and then leaves an empty 'db.xml' which won't work. Can anyone
> here help me figure out why this is?
> Stuff I've done:
> I've traced this down to the self.commit() call in __del__. The
> stacktrace and a few print statements injected into xml.etree leads me
> to the call 'root'.encode('us-ascii') throwing a LookupError on line 751
> of xml.etree.ElementTree. This makes no sense to me, since it works fine
> normally.

The environment available to __del__ methods during program termination
is wonky, and apparently not very consistent either. I can't say that I
completely understand it myself, perhaps someone else can provide a
better explanation for both of us, but some of the causes are described
in the documentation:


What is your rationale for using __del__? Are you trying to force a
'commit()' call on Database instances when your program terminates -- in
the case of an unhandled exception, for example?


> Thank you very much. Any and all help or pointers are appreciated.
> ~Matt
> #### db.py ###
> from xml.etree import ElementTree as ET
> import os
> class Database(object):
>     def __init__(self, path):
>         self.__dbpath = path    ## Path to the database
>         self.load()
>     def __del__(self):
>         ## FIXME: Known bug:
>         ##  del db at command line works properly
>         ##  Ctrl-D, when there is no db file present, results in a
> LookupError
>         ##    and empty xml file
>         from StringIO import StringIO
>         from traceback import print_exc
>         trace = StringIO()
>         try:
>             print 5
>             self.commit()
>             print 7
>         except Exception:
>             print_exc(100, trace)
>             print trace.getvalue()
>     def load(self):
>         if os.path.exists(self.__dbpath):
>             self.root = ET.parse(self.__dbpath).getroot()
>         else:
>             self.root = ET.Element("root")
>     def commit(self):
>         ET.ElementTree(self.root).write(self.__dbpath)
> db = Database('db.xml')

More information about the Tutor mailing list