import xml sax saxutils class XmlShadow def __init__ self attribute_na

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
import xml.sax.saxutils
class XmlShadow:
def __init__(self, attribute_name):
self.attribute_name = attribute_name
def __get__(self, instance, owner=None):
return xml.sax.saxutils.escape(
getattr(instance, self.attribute_name))
class Product:
__slots__ = ("__name", "__description", "__price")
name_as_xml = XmlShadow("name")
description_as_xml = XmlShadow("description")
def __init__(self, name, description, price):
self.__name = name
self.description = description
self.price = price
@property
def name(self):
return self.__name
@property
def description(self):
return self.__description
@description.setter
def description(self, description):
self.__description = description
@property
def price(self):
return self.__price
@price.setter
def price(self, price):
self.__price = price
class CachedXmlShadow:
def __init__(self, attribute_name):
self.attribute_name = attribute_name
self.cache = {}
def __get__(self, instance, owner=None):
xml_text = self.cache.get(id(instance))
if xml_text is not None:
return xml_text
return self.cache.setdefault(id(instance),
xml.sax.saxutils.escape(
getattr(instance, self.attribute_name)))
class CachedProduct:
__slots__ = ("__name", "__description", "__price")
name_as_xml = CachedXmlShadow("name")
description_as_xml = CachedXmlShadow("description")
def __init__(self, name, description, price):
self.__name = name
self.description = description
self.price = price
@property
def name(self):
return self.__name
@property
def description(self):
return self.__description
@description.setter
def description(self, description):
self.__description = description
@property
def price(self):
return self.__price
@price.setter
def price(self, price):
self.__price = price
if __name__ == "__main__":
import doctest
doctest.testmod()