Whitespace normalization.
[python/dscho.git] / Lib / xml / dom / minicompat.py
blob9f2f8f76271d7e37e7c003ba13b9cf85bbbdb935
1 """Python version compatibility support for minidom."""
3 # This module should only be imported using "import *".
5 # The following names are defined:
7 # isinstance -- version of the isinstance() function that accepts
8 # tuples as the second parameter regardless of the
9 # Python version
11 # NodeList -- lightest possible NodeList implementation
13 # EmptyNodeList -- lightest possible NodeList that is guarateed to
14 # remain empty (immutable)
16 # StringTypes -- tuple of defined string types
18 # GetattrMagic -- base class used to make _get_<attr> be magically
19 # invoked when available
20 # defproperty -- function used in conjunction with GetattrMagic;
21 # using these together is needed to make them work
22 # as efficiently as possible in both Python 2.2+
23 # and older versions. For example:
25 # class MyClass(GetattrMagic):
26 # def _get_myattr(self):
27 # return something
29 # defproperty(MyClass, "myattr",
30 # "return some value")
32 # For Python 2.2 and newer, this will construct a
33 # property object on the class, which avoids
34 # needing to override __getattr__(). It will only
35 # work for read-only attributes.
37 # For older versions of Python, inheriting from
38 # GetattrMagic will use the traditional
39 # __getattr__() hackery to achieve the same effect,
40 # but less efficiently.
42 # defproperty() should be used for each version of
43 # the relevant _get_<property>() function.
45 # NewStyle -- base class to cause __slots__ to be honored in
46 # the new world
48 # True, False -- only for Python 2.2 and earlier
50 __all__ = ["NodeList", "EmptyNodeList", "NewStyle",
51 "StringTypes", "defproperty", "GetattrMagic"]
53 import xml.dom
55 try:
56 unicode
57 except NameError:
58 StringTypes = type(''),
59 else:
60 StringTypes = type(''), type(unicode(''))
63 # define True and False only if not defined as built-ins
64 try:
65 True
66 except NameError:
67 True = 1
68 False = 0
69 __all__.extend(["True", "False"])
72 try:
73 isinstance('', StringTypes)
74 except TypeError:
76 # Wrap isinstance() to make it compatible with the version in
77 # Python 2.2 and newer.
79 _isinstance = isinstance
80 def isinstance(obj, type_or_seq):
81 try:
82 return _isinstance(obj, type_or_seq)
83 except TypeError:
84 for t in type_or_seq:
85 if _isinstance(obj, t):
86 return 1
87 return 0
88 __all__.append("isinstance")
91 if list is type([]):
92 class NodeList(list):
93 __slots__ = ()
95 def item(self, index):
96 if 0 <= index < len(self):
97 return self[index]
99 def _get_length(self):
100 return len(self)
102 def _set_length(self, value):
103 raise xml.dom.NoModificationAllowedErr(
104 "attempt to modify read-only attribute 'length'")
106 length = property(_get_length, _set_length,
107 doc="The number of nodes in the NodeList.")
109 def __getstate__(self):
110 return list(self)
112 def __setstate__(self, state):
113 self[:] = state
115 class EmptyNodeList(tuple):
116 __slots__ = ()
118 def __add__(self, other):
119 NL = NodeList()
120 NL.extend(other)
121 return NL
123 def __radd__(self, other):
124 NL = NodeList()
125 NL.extend(other)
126 return NL
128 def item(self, index):
129 return None
131 def _get_length(self):
132 return 0
134 def _set_length(self, value):
135 raise xml.dom.NoModificationAllowedErr(
136 "attempt to modify read-only attribute 'length'")
138 length = property(_get_length, _set_length,
139 doc="The number of nodes in the NodeList.")
141 else:
142 def NodeList():
143 return []
145 def EmptyNodeList():
146 return []
149 try:
150 property
151 except NameError:
152 def defproperty(klass, name, doc):
153 # taken care of by the base __getattr__()
154 pass
156 class GetattrMagic:
157 def __getattr__(self, key):
158 if key.startswith("_"):
159 raise AttributeError, key
161 try:
162 get = getattr(self, "_get_" + key)
163 except AttributeError:
164 raise AttributeError, key
165 return get()
167 class NewStyle:
168 pass
170 else:
171 def defproperty(klass, name, doc):
172 get = getattr(klass, ("_get_" + name)).im_func
173 def set(self, value, name=name):
174 raise xml.dom.NoModificationAllowedErr(
175 "attempt to modify read-only attribute " + repr(name))
176 assert not hasattr(klass, "_set_" + name), \
177 "expected not to find _set_" + name
178 prop = property(get, set, doc=doc)
179 setattr(klass, name, prop)
181 class GetattrMagic:
182 pass
184 NewStyle = object