Fix sf bug 666219: assertion error in httplib.
[python/dscho.git] / Lib / UserString.py
blobfcd115d005fa27fca33e5e9ec44360b65a958852
1 #!/usr/bin/env python
2 ## vim:ts=4:et:nowrap
3 """A user-defined wrapper around string objects
5 Note: string objects have grown methods in Python 1.6
6 This module requires Python 1.6 or later.
7 """
8 from types import StringTypes
9 import sys
11 __all__ = ["UserString","MutableString"]
13 class UserString:
14 def __init__(self, seq):
15 if isinstance(seq, StringTypes):
16 self.data = seq
17 elif isinstance(seq, UserString):
18 self.data = seq.data[:]
19 else:
20 self.data = str(seq)
21 def __str__(self): return str(self.data)
22 def __repr__(self): return repr(self.data)
23 def __int__(self): return int(self.data)
24 def __long__(self): return long(self.data)
25 def __float__(self): return float(self.data)
26 def __complex__(self): return complex(self.data)
27 def __hash__(self): return hash(self.data)
29 def __cmp__(self, string):
30 if isinstance(string, UserString):
31 return cmp(self.data, string.data)
32 else:
33 return cmp(self.data, string)
34 def __contains__(self, char):
35 return char in self.data
37 def __len__(self): return len(self.data)
38 def __getitem__(self, index): return self.__class__(self.data[index])
39 def __getslice__(self, start, end):
40 start = max(start, 0); end = max(end, 0)
41 return self.__class__(self.data[start:end])
43 def __add__(self, other):
44 if isinstance(other, UserString):
45 return self.__class__(self.data + other.data)
46 elif isinstance(other, StringTypes):
47 return self.__class__(self.data + other)
48 else:
49 return self.__class__(self.data + str(other))
50 def __radd__(self, other):
51 if isinstance(other, StringTypes):
52 return self.__class__(other + self.data)
53 else:
54 return self.__class__(str(other) + self.data)
55 def __mul__(self, n):
56 return self.__class__(self.data*n)
57 __rmul__ = __mul__
58 def __mod__(self, args):
59 return self.__class__(self.data % args)
61 # the following methods are defined in alphabetical order:
62 def capitalize(self): return self.__class__(self.data.capitalize())
63 def center(self, width): return self.__class__(self.data.center(width))
64 def count(self, sub, start=0, end=sys.maxint):
65 return self.data.count(sub, start, end)
66 def decode(self, encoding=None, errors=None): # XXX improve this?
67 if encoding:
68 if errors:
69 return self.__class__(self.data.decode(encoding, errors))
70 else:
71 return self.__class__(self.data.decode(encoding))
72 else:
73 return self.__class__(self.data.decode())
74 def encode(self, encoding=None, errors=None): # XXX improve this?
75 if encoding:
76 if errors:
77 return self.__class__(self.data.encode(encoding, errors))
78 else:
79 return self.__class__(self.data.encode(encoding))
80 else:
81 return self.__class__(self.data.encode())
82 def endswith(self, suffix, start=0, end=sys.maxint):
83 return self.data.endswith(suffix, start, end)
84 def expandtabs(self, tabsize=8):
85 return self.__class__(self.data.expandtabs(tabsize))
86 def find(self, sub, start=0, end=sys.maxint):
87 return self.data.find(sub, start, end)
88 def index(self, sub, start=0, end=sys.maxint):
89 return self.data.index(sub, start, end)
90 def isalpha(self): return self.data.isalpha()
91 def isalnum(self): return self.data.isalnum()
92 def isdecimal(self): return self.data.isdecimal()
93 def isdigit(self): return self.data.isdigit()
94 def islower(self): return self.data.islower()
95 def isnumeric(self): return self.data.isnumeric()
96 def isspace(self): return self.data.isspace()
97 def istitle(self): return self.data.istitle()
98 def isupper(self): return self.data.isupper()
99 def join(self, seq): return self.data.join(seq)
100 def ljust(self, width): return self.__class__(self.data.ljust(width))
101 def lower(self): return self.__class__(self.data.lower())
102 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
103 def replace(self, old, new, maxsplit=-1):
104 return self.__class__(self.data.replace(old, new, maxsplit))
105 def rfind(self, sub, start=0, end=sys.maxint):
106 return self.data.rfind(sub, start, end)
107 def rindex(self, sub, start=0, end=sys.maxint):
108 return self.data.rindex(sub, start, end)
109 def rjust(self, width): return self.__class__(self.data.rjust(width))
110 def rstrip(self, chars=None): return self.__class__(self.data.rstrip(chars))
111 def split(self, sep=None, maxsplit=-1):
112 return self.data.split(sep, maxsplit)
113 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
114 def startswith(self, prefix, start=0, end=sys.maxint):
115 return self.data.startswith(prefix, start, end)
116 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
117 def swapcase(self): return self.__class__(self.data.swapcase())
118 def title(self): return self.__class__(self.data.title())
119 def translate(self, *args):
120 return self.__class__(self.data.translate(*args))
121 def upper(self): return self.__class__(self.data.upper())
122 def zfill(self, width): return self.__class__(self.data.zfill(width))
124 class MutableString(UserString):
125 """mutable string objects
127 Python strings are immutable objects. This has the advantage, that
128 strings may be used as dictionary keys. If this property isn't needed
129 and you insist on changing string values in place instead, you may cheat
130 and use MutableString.
132 But the purpose of this class is an educational one: to prevent
133 people from inventing their own mutable string class derived
134 from UserString and than forget thereby to remove (override) the
135 __hash__ method inherited from ^UserString. This would lead to
136 errors that would be very hard to track down.
138 A faster and better solution is to rewrite your program using lists."""
139 def __init__(self, string=""):
140 self.data = string
141 def __hash__(self):
142 raise TypeError, "unhashable type (it is mutable)"
143 def __setitem__(self, index, sub):
144 if index < 0 or index >= len(self.data): raise IndexError
145 self.data = self.data[:index] + sub + self.data[index+1:]
146 def __delitem__(self, index):
147 if index < 0 or index >= len(self.data): raise IndexError
148 self.data = self.data[:index] + self.data[index+1:]
149 def __setslice__(self, start, end, sub):
150 start = max(start, 0); end = max(end, 0)
151 if isinstance(sub, UserString):
152 self.data = self.data[:start]+sub.data+self.data[end:]
153 elif isinstance(sub, StringTypes):
154 self.data = self.data[:start]+sub+self.data[end:]
155 else:
156 self.data = self.data[:start]+str(sub)+self.data[end:]
157 def __delslice__(self, start, end):
158 start = max(start, 0); end = max(end, 0)
159 self.data = self.data[:start] + self.data[end:]
160 def immutable(self):
161 return UserString(self.data)
162 def __iadd__(self, other):
163 if isinstance(other, UserString):
164 self.data += other.data
165 elif isinstance(other, StringTypes):
166 self.data += other
167 else:
168 self.data += str(other)
169 return self
170 def __imul__(self, n):
171 self.data *= n
172 return self
174 if __name__ == "__main__":
175 # execute the regression test to stdout, if called as a script:
176 import os
177 called_in_dir, called_as = os.path.split(sys.argv[0])
178 called_as, py = os.path.splitext(called_as)
179 if '-q' in sys.argv:
180 from test import test_support
181 test_support.verbose = 0
182 __import__('test.test_' + called_as.lower())