Productively Distracted
Posted Wednesday June 22, 2011 around 11:28 PM

I am pleased to announce the first stable release of datatree. I started datatree to cut down on the amount of line noise needed to create xml in python. I had recently used builder in ruby and was impressed with its brevity and aesthetics. So I set out to create something similar in python.

Consider the following 2 examples. First with elementtree:

import xml.etree.ElementTree as e

author = e.Element("author")
name = e.SubElement(author, "name")
name.text = "Terry Pratchett"
genre = e.SubElement(author, "genre")
genre.text = "Fantasy/Comedy"
author.append(e.Comment("Only 2 books listed"))
novels = e.SubElement(author, "novels", count="2")
small_gods = e.SubElement(novels, "novel", year="1992")
small_gods.text = "Small Gods"
fifth_elephant = e.SubElement(novels, "novel", year="1999")
fifth_elephant.text = "The Fifth Elephant"
guards_guards = e.SubElement(novels, "novel", year="1989")
guards_guards.text = "Guards! Guards!"
Download

And then with datatree:

from datatree.tree import Tree, Node

with Tree().author() as author:
    author.name('Terry Pratchett')
    author.genre('Fantasy/Comedy')
    author // "Only 2 books listed"
    with author.novels(count=2) as novels:
        novels.novel('Small Gods', year=1992)
        novels.novel('The Fifth Elephant', year=1999)
        novels.novel("Guards! Guards!", year=1989)
Download

Both of these will output the exact same xml document, but datatree does it in fewer lines and the code is significantly easier to read. It also occurred to me that I spend a lot of time producing structured data in multiple formats. So I added the ability to render the tree into multiple formats. The above Tree can be output in json or yaml with no code changes at all. Additionally new formats can be added with an extensible API.

The library is by no means exhaustive yet, but it is in a usable state. We are using it in production at my day job and having great success with it. I would love to hear feedback. Best way to get me is on twitter: @BigJasonWebb.

Links:

Update 6/23/2011 8:00 AM: I have heard some concerns about the choice of license, Creative Commons 3.0. This seemed like a good idea to me, but I am rather new to open source and may not understand all the implications. If anyone can suggest a better license that would make the library more accessible for everyone, I would be very open to changing it.

Update 6/23/2011 3:00 PM: The license has been changed to Apache License, Version 2.0 effective immediately. Thanks for all the feedback and suggestions.

blog comments powered by Disqus