Ron Adam wrote:
> 
> 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?



The following worked in cases where I needed to append a list of items.

def extend(e1, elist):
     for e in elist:
         e1.append(e)
     return e1


Although I still need to return the list as elements aren't mutable.

     element = extend(element, elist)

It would be nice if this was built in so I could do...  Hint hint.  :-)

     element.extend(elist)

Where elist is a list of elements or an element with a number of sub 
elements.


I still need to special case individual appends or put the returned item 
in a list so I use the extend() function on the returned element.

I guess I need to look at the Element Tree source code.

Cheers,
    Ron









-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to