Appending Elements in Element Tree

Ron Adam rrr at ronadam.com
Fri Apr 7 21:29:52 EDT 2006


In my program I have a lot of statements that append elements, but 
sometimes I don't want to append the element so it requres an if 
statement to check it, and that requires assigning the returned element 
from a function to a name or calling the funtion twice.

     e = ET.Element('name')
     e.append(get_subelement(obj))   # but raises an exception on None



This works, but I have a lot of appends.

     sube = get_element(obj)
     if sube is None:
         e.append(sube)



Now if Elements worked more like lists I could extend an element.

     alist = []
     alist.extend([])    # returns orginal list



With strings.

     s = ''
     s += ''  # returns original string (or copy)


So is there an identity operation with Element Tree elements that I can 
use to avoid putting a lot of if and or try statements around appending 
elements?



I could wrap the append and do it this way...

    def eappend(e1, e2):
       if e2 is None: return e1
       e1.append(e2)
       return e1

Then do...

    e = eappend(e, get_element(obj))   # Append if not None.


But maybe there's a better way?


Ron








More information about the Python-list mailing list