Saturday, 12 December 2015

XML : How to override a method on an existing class in python3?

I'm writing an application that uses python's xml.etree.ElementTree.Element class to represent internal data. In some cases I build the data tree at runtime from code, and in other cases I read the data in from an xml file using xml.etree.ElementTree.parse().

I want to override the class's __getitem__ method so that I can access elements using string indicies as a short hand like I would with a dict. so I've tried this:

  class MyElement(ET.Element):      '''      Simple extension of Element type to allow accessing data by string key      like in a dict."    '''      def __init__(self, *args, **kwargs):      super(MyElement, self).__init__(args)      def __getitem__(self, tag):      if type(tag) == str:        return self.find(tag).text      else:        return ET.Element.__getitem__(self, tag)    

When I build my data up in code, I use my new class and it works great. But when I use the parse method, it returns a standard ET.Element. I would like a way to "convert" the ET.Element to my new subclass.

I've tried directly changing class which does not work in python3 and feel hacky anyway. I've also read about composition and creating a class that has ET.Element as an attribute instead, but I think using myInstance.EtreeMember.tag instead of myInstance.tag misrepresents the data's purpose, and is enough typing that it eliminates the convenience of the short hand bracket notation.

So, my question is whether any of the following are possible: 1. Initialize my class from an existing instance of ET.Element 2. Cast an ET.Element into my new subclass. 3. Make parse (or some wrapper for it that I'm willing to write) return my subclass instead of ET.Element

No comments:

Post a Comment