[IronPython] try...finally in yield

Curt Hagenlocher curt at hagenlocher.org
Sun Mar 29 04:39:23 CEST 2009

So I assume you're calling close() on the generator?  A try/finally around
the code in the generator can be used to catch the StopIteration exception
and force the dispose.  But even better, you could say "from __future__
import with_statement" at the top of your file and then say something like

def parse(xml):
    with XmlReader.Create(xml) as xr
        while xr.Read():

We automatically do the right thing when using "with" and IDisposable, so
"with" effectively becomes like a C# "using" block.

2009/3/28 Adam Brand <adamb at silverkeytech.com>

> 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
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20090328/f437428b/attachment.html>

More information about the Ironpython-users mailing list