Assign Objects to Element Attributes in elementtree

| Comments

You can store pretty much anything as an attribute of an elementtree Element instance, not just strings.
A recent comment got me experimenting with this. Tom mentioned “Attributes can only be text”, which is abso-smurfly correct for XML. But remember: ElementTree is not XML. If you don’t need to serialize to XML, you can hang whatever you like on Elements.

Extending my power plant elementtree example a bit, I create a simple class to represent an employee, then hang instances of it on elements in a nested structure:

from elementtree.ElementTree import Element
from elementtree.ElementTree import SubElement

class Emp(object):
    """A simple Employee

    def __init__(self, name, title): = name
        self.title = title

# make some employee instances
burns = Emp("Monty", "CEO")
smithers = Emp("Waylon", "Flunkie")
karl = Emp("Carl", "Engineer")
lenny = Emp("Lenny", "Engineer")
homer = Emp("Homer","Safety Inspector")

# hang them on a tree
ceo = Element('e', emp=burns)
smithers_elem = SubElement(ceo, 'e', emp=smithers)
SubElement(smithers_elem, 'e', emp=karl)
SubElement(smithers_elem, 'e', emp=lenny)
SubElement(smithers_elem, 'e', emp=homer)

It’s gross because I create element labels that will never be used (“e”), and I can’t ever serialize the structure to XML (bummer), but if you need nested data in a hurry, it’s hard to beat.

Plus, I’m pretty sure that someone smarter than I could make this scenario cleaner by doing things like extending tostring to correctly serialize the Emp instances.

blog comments powered by Disqus