.comment-link {margin-left:.6em;} <$BlogRSDURL$>

Wednesday, December 01, 2004

Getting Geeky 

In real life I write bioinformatics software. My language of choice is God's Own Programming Language: Python. Lately I've felt the need to get a pile of tab-delimited files combined into a single, useful file and decided that XML was the way to go. I headed off to The Python Cookbook to see if they had any light weight XML code (the xml.dom and sax stuff is just a bit to burly for what I need) and found a lovely class that represents everything in a tree of instances. But, alas, it didn't include a __repr__ method. So I wrote one I'm quite proud of and am sharing it here with you:

def __repr__(self, indent = 0):
"""
) __repr__(self, indent = 0)
)
) Generates a string to print. If the given element has children they are also
) printed. The optional indent parameter gets used when children are printed
) and makes them be indented in a pleasing manner.
)
) Parameters:
) indent - the number of blank spaces to put in front of the printed information
)
) Returns: a string to print
"""
indentDelta = 4 # The depth of indenting for children and cdata

string = "%s<%s" % (indent * ' ', self.name)
for attName in self.attributes:
# Put the attributes, if any, inside the starting tag
string += ' %s = "%s"' % (attName, self.attributes[attName])

if self.cdata or self.children:
string += ">\n"
if self.cdata:
# Print the cdata so that it is indented as much as the children will be
string += "%s%s\n" % ((indent + indentDelta) * ' ', self.cdata)

for child in self.children:
# Print all the children of the current tag with a pleasing indent
string += child.__repr__(indent = indent + indentDelta)

string += "%s</%s>\n" % (indent * ' ', self.name)
else:
# If the string has neither children nor cdata, close it with the
# no-closing-tag-required ending
string += " />\n"

return string
## __repr__ ##

Comments: Post a Comment


Links to this post:

Create a Link

This page is powered by Blogger. Isn't yours?