[IronPython] try...finally in yield

Adam Brand adamb at silverkeytech.com
Sun Mar 29 03:02:55 CEST 2009


I'm using IronPython for ASP.Net...have some code (not mine,
http://devhawk.net/2008/05/07/Deserializing+XML+With+IronPython.aspx - Harry
Pierson's) that converts an xml file into an object. It has the below
function:

def parse(xml):
    xr = XmlReader.Create(xml)
    while xr.Read():
        xr.MoveToContent()
        node = XmlNode(xr)
        yield node
        if (xr.IsEmptyElement):
            node.nodeType = XmlNodeType.EndElement
            del node.attributes
            yield node

This code is problematic as it locks the xml file it is reading. I tried a
try...finally to do a .Close() and .Dispose(), but the compiler was not
happy with that. Just putting .Close() and .Dispose() at the end doesn't
work.

In reading up, I found this:
http://docs.python.org/whatsnew/2.5.html#pep-342

"The addition of the close() method has one side effect that isn’t obvious.
close() is called when a generator is garbage-collected, so this means the
generator’s code gets one last chance to run before the generator is
destroyed. This last chance means that try...finally statements in
generators can now be guaranteed to work; the finally clause will now always
get a chance to run. The syntactic restriction that you couldn’t mix yield
statements with a try...finally suite has therefore been removed. "

I'm guessing that this isn't implemented in the version of IronPython in IP
for ASP.Net.

Does anyone have any ideas on a workaround for the generator for this
version?

Thanks,
Adam

-- 
Adam Brand
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20090328/62786cc0/attachment.html>


More information about the Ironpython-users mailing list