简体   繁体   中英

Extending functionality of Element and ElementTree

I would like to extend the functionality of Element and ElementTree classes from xml.etree and use them with xml.etree.ElementTree.parse() .

After a few tries, I've managed to create a solution for that problem, but I would like to know if there is a better solution or if this one has any hidden dangers.

FooElementTree.py

import xml.etree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import ElementTree

class FooElement(Element):
    def __repr__(self):
        return "<FooElement %s at 0x%x>" % (repr(self.tag), id(self))

class FooElementTree(ElementTree):
    pass

xml.etree.ElementTree.Element = FooElement
xml.etree.ElementTree.ElementTree = FooElementTree
from xml.etree.ElementTree import parse

Usage:

>>> import FooElementTree
>>> e = FooElementTree.parse('xml.cfg')
>>> e
<FooElementTree.FooElementTree object at 0x023AB650>
>>> r = e.getroot()
>>> r
<FooElement 'configuration' at 0x23c5470>

This is the way, hot patching works. But be aware, that the patch has to be applied before any other Module (or Submodule) is imported, that uses ElementTree, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM