[Tutor] String Encoding problem

Kent Johnson kent37 at tds.net
Mon Apr 20 22:50:22 CEST 2009


On Mon, Apr 20, 2009 at 10:46 AM, Matt <HellZFury+Python at gmail.com> wrote:
> 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.

Please show the exact error message and stack trace when you post
errors, it can be very helpful.

What you are doing with __del__ is unusual and not common practice. A
better way to ensure cleanup is to use a close() method which a client
must call, or to use a context manager and 'with' statement.

I think the reason your code is failing is because some module needed
by the encode() call has already been unloaded before your __del__()
method is called.
>
> Thank you very much. Any and all help or pointers are appreciated.

If you defined a close() method, you could write client code like this:

from contextlib import closing
with closing(Database('db.xml')) as db:
  # do something with db
  # when this block exits db will be closed

It's also not too hard to make an openDatabase() function so you could write
with (openDatabase('db.xml')) as db:
  # etc

though that is not really a beginner challenge. Some notes and further
pointers here:
http://personalpages.tds.net/~kent37/kk/00015.html

Kent


More information about the Tutor mailing list