comparison emeraldtree/ElementTree.py @ 41:f9fe97f25af0

ElementTree - Derive QName from unicode
author Bastian Blank <bblank@thinkmo.de>
date Thu, 24 Jul 2008 09:40:07 +0200
parents 5784bad989d1
children 53378e9b1814
comparison
equal deleted inserted replaced
40:a8382b8cded5 41:f9fe97f25af0
476 # QName wrapper. This can be used to wrap a QName attribute value, in 476 # QName wrapper. This can be used to wrap a QName attribute value, in
477 # order to get proper namespace handling on output. 477 # order to get proper namespace handling on output.
478 # 478 #
479 # @return An opaque object, representing the QName. 479 # @return An opaque object, representing the QName.
480 480
481 class QName(object): 481 class QName(unicode):
482 __slots__ = 'text', 'name', 'uri' 482 __slots__ = 'name', 'uri'
483 483
484 def __init__(self, text, uri=None): 484 def __new__(cls, name, uri=None):
485 text = unicode(text) 485 text = name = unicode(name)
486 if text[0] == '{': 486
487 if name[0] == '{':
487 if uri is not None: 488 if uri is not None:
488 raise ValueError 489 raise ValueError
489 i = text.find('}') 490 i = name.find('}')
490 if i == -1: 491 if i == -1:
491 raise ValueError 492 raise ValueError
492 uri = text[1:i] 493 uri = name[1:i]
493 text = text[i + 1:] 494 name = name[i + 1:]
494 self.name, self.uri = text, uri 495
495 496 if uri is not None:
496 if self.uri is not None: 497 text = '{' + uri + '}' + name
497 self.text = '{' + self.uri + '}' + self.name 498
498 else: 499 ret = unicode.__new__(cls, text)
499 self.text = self.name 500 unicode.__setattr__(ret, 'name', name)
501 unicode.__setattr__(ret, 'uri', uri)
502
503 return ret
504
505 def __getnewargs__(self):
506 return self.name, self.uri
507
508 def __getstate__(self):
509 pass
500 510
501 def __repr__(self): 511 def __repr__(self):
502 return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.uri) 512 return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.uri)
503 513
504 def __str__(self): 514 def __setattr__(self, key, value):
505 return self.text 515 raise AttributeError('read-only')
506
507 def __hash__(self):
508 return hash(self.text)
509
510 def __cmp__(self, other):
511 if isinstance(other, QName):
512 return cmp(self.text, other.text)
513 return cmp(self.text, other)
514 516
515 def copy(self): 517 def copy(self):
516 return self.__class__(self.name, self.uri) 518 return self.__class__(self.name, self.uri)
519
520 @property
521 def text(self):
522 return self
517 523
518 # -------------------------------------------------------------------- 524 # --------------------------------------------------------------------
519 525
520 ## 526 ##
521 # ElementTree wrapper class. This class represents an entire element 527 # ElementTree wrapper class. This class represents an entire element