public
Last active

Code for better cloning of ElementTree (XML) objects in Python

  • Download Gist
ElementTree cloning factory
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import xml.etree.cElementTree as ET
 
"""
ripped off from:
http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/clone.py
 
apparently this is faster than using copy.deepcopy on an ElementTree
"""
 
##
# Turns an element tree into a cloning factory. The callable object
# returned by this function returns copies of the original tree.
#
# @param elem An element tree.
# @return A callable factory object.
 
def make_factory(elem):
def generate_elem(append, elem, level):
var = "e" + str(level)
arg = repr(elem.tag)
if elem.attrib:
arg += ", **%r" % elem.attrib
if level == 1:
append(" e1 = Element(%s)" % arg)
else:
append(" %s = SubElement(e%d, %s)" % (var, level-1, arg))
if elem.text:
append(" %s.text = %r" % (var, elem.text))
if elem.tail:
append(" %s.tail = %r" % (var, elem.tail))
for e in elem:
generate_elem(append, e, level+1)
# generate code for a function that creates a tree
output = ["def element_factory():"]
generate_elem(output.append, elem, 1)
output.append(" return e1")
# setup global function namespace
namespace = {"Element": ET.Element, "SubElement": ET.SubElement}
# create function object
exec "\n".join(output) in namespace
return namespace["element_factory"]
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import xml.etree.cElementTree as ET
 
"""
ripped off from:
http://effbot.python-hosting.com/file/stuff/sandbox/elementlib/clone.py
 
apparently this is faster than using copy.deepcopy on an ElementTree
"""
 
##
# Turns an element tree into a cloning factory. The callable object
# returned by this function returns copies of the original tree.
#
# @param elem An element tree.
# @return A callable factory object.
 
def make_factory(elem):
def generate_elem(append, elem, level):
var = "e" + str(level)
arg = repr(elem.tag)
if elem.attrib:
arg += ", **%r" % elem.attrib
if level == 1:
append(" e1 = Element(%s)" % arg)
else:
append(" %s = SubElement(e%d, %s)" % (var, level-1, arg))
if elem.text:
append(" %s.text = %r" % (var, elem.text))
if elem.tail:
append(" %s.tail = %r" % (var, elem.tail))
for e in elem:
generate_elem(append, e, level+1)
# generate code for a function that creates a tree
output = ["def element_factory():"]
generate_elem(output.append, elem, 1)
output.append(" return e1")
# setup global function namespace
namespace = {"Element": ET.Element, "SubElement": ET.SubElement}
# create function object
exec "\n".join(output) in namespace
return namespace["element_factory"]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.