Featured post
python - lxml objectify does not call constructors for custom element classes -
lxml.objectify not seem call constructors custom element classes:
from lxml import objectify, etree class customlookup(etree.customelementclasslookup): def lookup(self, node_type, document, namespace, name): lookupmap = { 'custom' : customelement } try: return lookupmap[name] except keyerror: return none class customelement(etree.elementbase): def __init__(self): print("made customelement") parser = objectify.makeparser() parser.set_element_class_lookup(customlookup()) root = objectify.parse(fname,parser).getroot()
suppose file being parsed is
<custom />
i print "made customelement", not. can make call constructor?
how possible instance of customelement class created without constructor being called?
>>> isinstance(root,customelement) true
from lxml
docs:
element initialization
there 1 thing know front. element classes must not have
__init___
or__new__
method. there should not internal state either, except data stored in underlying xml tree. element instances created , garbage collected @ need, there no way predict when , how proxy created them. worse, when__init__
method called, object not initialized yet represent xml tag, there not use in providing__init__
method in subclasses.most use cases not require class initialisation, can content skipping next section now. however, if need set element class on instantiation, there 1 possible way so. elementbase classes have
_init()
method can overridden. can used modify xml tree, e.g. construct special children or verify , update attributes.the semantics of
_init()
follows:
it called once on element class instantiation time. is, when python representation of element created lxml. @ time, element object initialized represent specific xml element within tree.
the method has complete access xml tree. modifications can done in same way anywhere else in program.
python representations of elements may created multiple times during lifetime of xml element in underlying c tree.
_init()
code provided subclasses must take special care multiple executions either harmless or prevented kind of flag in xml tree. latter can achieved modifying attribute value or removing or adding specific child node , verifying before running through init process.any exceptions raised in
_init()
propagated throught api call lead creation of element. careful code write here exceptions may turn in various unexpected places.
- Get link
- X
- Other Apps
Comments
Post a Comment