Saturday, February 28, 2009

Writing Xml with IronPython, XmlWriter and the 'with' statement

One of the best things about IronPython 2 is that it is based on Python 2.5 rather than 2.4. Amongst other goodies this means that the with statement is available. The with statement is the equivalent of C#'s using statement, although the Python context management protocol methods give a finer degree of control over exception handling.

The with statement makes resource initialization and clean up simpler, and it will be nice to start using it throughout the Resolver One code base. It can often be used to replace the use of decorators or explicit try finally blocks, and many objects in the Python standard library have the necessary context manager methods to be used with "with".

Luis Diego Fallas has written a great blog entry demonstrating 'with' with the XML classes provided by System.Xml:
He creates a small wrapper class that provides the __enter__ and __exit__ methods used by the context mangement protocol, so that he can use with and the XmlWriter for the creation of SVG files.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.