# # Gives a NPE under Jython 2.5rc4 with "Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_14" # # Python 2.5.x / 2.6.x: # JyHandler: # ok # WorkaroundHandler: # ok # PyHandler: # ok # # Jython 2.5: # JyHandler: # Expected None for ('', attrs) # WorkaroundHandler: # ok # PyHandler: # NPE # from xml.sax import handler, make_parser from StringIO import StringIO class JyHandler(handler.ContentHandler): def startElementNS(self, name, qname, attrs): if attrs.get(('', 'attr')) is not None: raise Exception("Expected None for ('', attrs)") class PyHandler(handler.ContentHandler): def startElementNS(self, name, qname, attrs): if attrs.get((None, 'attr')) is None: error() class WorkaroundHandler(handler.ContentHandler): def startElementNS(self, name, qname, attrs): if attributes(attrs).get((None, 'attr')) is None: error() def ok(): print ' ok' def error(): raise Exception('No "attr"') import sys if sys.platform[:4] == 'java': # Jython's SAX implementation behaves differently from CPython. The Java # SAX parsers expect an empty string not ``None`` for the namespace # This work-around lets Jython accept "attrs.get((None, 'myattr')) instead # of "attrs.get(('', 'myattr')) from xml.sax.drivers2.drv_javasax import AttributesNSImpl #pylint: disable-msg=E0611, F0401 class AttrsImpl(AttributesNSImpl): def __init__(self, attrs): AttributesNSImpl.__init__(self, attrs._attrs) #pylint: disable-msg=W0212 def getValue(self, name): return AttributesNSImpl.getValue(self, (name[0] or '', name[1])) def attributes(attrs): """\ Returns an AttributesNS implementation which accepts ``None`` for the non-existent namespace IRI, i.e. ``getValue((None, 'myattr'))`` """ return AttrsImpl(attrs) else: def attributes(attrs): """\ Returns the attributes unmodified """ return attrs del sys def parse(content_handler): inp = '' parser = make_parser() parser.setFeature(handler.feature_namespaces, True) parser.setContentHandler(content_handler) parser.parse(StringIO(inp)) try: print 'JyHandler:' parse(JyHandler()) ok() except Exception, ex: print ex try: print 'WorkaroundHandler:' parse(WorkaroundHandler()) ok() except Exception, ex: print ex try: print 'PyHandler:' parse(PyHandler()) ok() except Exception, ex: print ex