473,804 Members | 4,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Subclassing cElementTree.XM LTreeBuilder

I found an earlier post about subclassing cElementTree.El ement which
can't
be done because it is a factory method. I am trying to subclass
XMLTreeBuilder
with success using the python implementation, but not with
cElementTree.

[1013]$ python
Python 2.3.4 (#1, Feb 22 2005, 04:09:37)
[GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
>>import elementtree.Ele mentTree
class X(elementtree.E lementTree.XMLT reeBuilder):
.... pass
....
>>import cElementTree
class Y(cElementTree. XMLTreeBuilder) :
.... pass
....
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot create 'builtin_functi on_or_method' instances
>>>
Is it possible to subclass cElementTree.XM LTreeBuilder?

Thanks,
Mike

Jan 25 '07 #1
2 2216
"mukappa" wrote:
Is it possible to subclass cElementTree.XM LTreeBuilder?
no, it's a factory function. if you need to extend it, you'll have to wrap it. but
I'm not sure I see the use case; what is it you're trying to do here?

</F>

Jan 25 '07 #2
On Jan 25, 4:32 am, "Fredrik Lundh" <fred...@python ware.comwrote:
"mukappa" wrote:
Is it possible to subclass cElementTree.XM LTreeBuilder?no , it's a factory function. if you need to extend it, you'll have to wrap it. but
I'm not sure I see the use case; what is it you're trying to do here?

</F>
I'm trying to parse xmpp stanzas coming in over a socket. Since
cElementTree is
more efficient, I would like to use it when available.

Here is what I have now:

import logging
from elementtree import ElementTree

class StanzaTreeBuild er(ElementTree. XMLTreeBuilder) :
"""Capture stanza elements (<streamchildre n) from parser events.

Private methods are lifted from the old
elementtree.XML TreeBuilder.Fan cyTreeBuilder
"""

def __init__(self, html=0):
"""Initiali ze state variables."""
ElementTree.XML TreeBuilder.__i nit__(self, html)
self._parser.St artNamespaceDec lHandler = self._start_ns
self._parser.En dNamespaceDeclH andler = self._end_ns
self.namespaces = []
self.level = 0
self.stanza = None
self.streamelem = None

def _start(self, tag, attrib_in):
elem = ElementTree.XML TreeBuilder._st art(self, tag, attrib_in)
self.start(elem )

def _start_list(sel f, tag, attrib_in):
elem = ElementTree.XML TreeBuilder._st art_list(self, tag,
attrib_in)
self.start(elem )

def _end(self, tag):
elem = ElementTree.XML TreeBuilder._en d(self, tag)
self.end(elem)

def _start_ns(self, prefix, value):
self.namespaces .insert(0, (prefix, value))

def _end_ns(self, prefix):
assert self.namespaces .pop(0)[0] == prefix, "implementa tion
confused"

def start(self, element):
"""Track nesting level (capture open <streamon first
call)."""
logging.debug(" start(%s): %s" %
(self.level, ElementTree.tos tring(element)) )
if self.streamelem is None:
assert element.tag == "http://etherx.jabber.o rg/streams"
self.streamelem = element
self.stanza = element
self.level += 1

def end(self, element):
"""Capture stanza when nesting level is 1."""
self.level -= 1
if self.level == 1:
self.stanza = element
self.streamelem .clear()
logging.debug(" end(%s): %s" %
(self.level, ElementTree.tos tring(element)) )

def stanzagen(socke t):
"""Yield open <stream ...on first call, then complete stanzas.

Caller needs 'id' from the opening <stream>, then he needs stanzas,
one per call. Works by parsing the socket one byte at a time, and
yielding complete stanza at earliest opportunity (or None if none
waiting), exits on EOF. Stanzas are returned as ElementTree
Elements
to give them a natural pythonic feel.

see
http://online.effbot.o rg/2004_12_01_arch ive.htm#element-generator"""
p = StanzaTreeBuild er()
data = None
while 1:
try:
data = socket.recv(1)
if not data:
logging.info("E OF from peer")
p.close()
break
p.feed(data)
if p.stanza is not None:
yield p.stanza
p.stanza = None
data = None
except:
if data is not None:
logging.error(" error reading: %s" % (data))
raise
else:
yield None

Jan 25 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5166
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this class which is supposed to be a representation of a genome: class Genome(list): def __init__(self): list.__init__(self) self = ....
1
1774
by: Kent Johnson | last post by:
Is it possible to subclass cElementTree.Element? I tried >>> import cElementTree as et >>> class Elt(et.Element): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances
11
3480
by: Brent | last post by:
I'd like to subclass the built-in str type. For example: -- class MyString(str): def __init__(self, txt, data): super(MyString,self).__init__(txt) self.data = data
27
1980
by: Igor V. Rafienko | last post by:
Hi, I am trying to understand how cElementTree's clear works: I have a (relatively) large XML file, that I do not wish to load into memory. So, naturally, I tried something like this: from cElementTree import iterparse for event, elem in iterparse("data.xml"): if elem.tag == "schnappi":
3
1890
by: Diez B. Roggisch | last post by:
Hi, I've got to deal with a pretty huge XML-document, and to do so I use the cElementTree.iterparse functionality. Working great. Only trouble: The guys creating that chunk of XML - well, lets just say they are "encodingly challanged", so they don't produce utf-8, but only cp1252 instead, together with some weird name (Windows-1252) for that. That is not part of the standard codecs module. cp1252 is, of course.
0
944
by: Mark | last post by:
I have an elementtree created with cElementTree. I then use ElementInclude to resolve some xinclude elements. But then I want to move those included elements to be children of the root root.append(included_child) but I get an error message TypeError: 'append() argument 1 must be Element, not instance'
0
1286
by: Mark | last post by:
-------- Original Message -------- Subject: Using cElementTree and elementtree.ElementInclude Date: Mon, 23 Oct 2006 09:40:24 -0500 From: Mark E. Smith <mark.e.smith@arnold.af.mil> Organization: AEDC To: python-list@python.org
1
1361
by: Piet van Oostrum | last post by:
I have just installed Python 2.5 on Mac OS X 10.4.8 on an iBook (PPC) from the dmg. Now I tried to install cElementTree -1.0.5-20 from source (no egg available in cheeseshop) and got the following compilation error: gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -DXML_STATIC -DHAVE_MEMMOVE=1 -DXML_NS=1...
1
2173
by: Barry | last post by:
I recently tried switching from ElementTree to cElementTree. My application parses a collection of large XML files and creates indexes based on certain attributes. This entire collection is saved as an instance of my Database class. Using ElementTree and cPickle has allowed me to save these instances and use them later. Using cElementTree significantly reduces parse time (~50%) and memory ~(15%) but cPickle refuses to pickle the...
0
9589
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9163
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7626
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6858
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5663
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3830
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3000
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.