blob: f74614534b2d3c874a5fcf72d5c11f9efc358d7e [file] [log] [blame]
Brett Cannon23a4a7b2008-05-12 00:56:28 +00001__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
2 'UserString']
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
4# They should however be considered an integral part of collections.py.
5from _abcoll import *
6import _abcoll
7__all__ += _abcoll.__all__
8
Christian Heimes99170a52007-12-19 02:07:34 +00009from _collections import deque, defaultdict
10from operator import itemgetter as _itemgetter
11from keyword import iskeyword as _iskeyword
12import sys as _sys
13
Raymond Hettinger48b8b662008-02-05 01:53:00 +000014################################################################################
15### namedtuple
16################################################################################
17
Guido van Rossum8ce8a782007-11-01 19:42:39 +000018def namedtuple(typename, field_names, verbose=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +000019 """Returns a new subclass of tuple with named fields.
20
Guido van Rossum8ce8a782007-11-01 19:42:39 +000021 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +000022 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +000023 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +000024 >>> p = Point(11, y=22) # instantiate with positional args or keywords
Christian Heimes99170a52007-12-19 02:07:34 +000025 >>> p[0] + p[1] # indexable like a plain tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000026 33
Christian Heimes99170a52007-12-19 02:07:34 +000027 >>> x, y = p # unpack like a regular tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000028 >>> x, y
29 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +000031 33
Christian Heimes0449f632007-12-15 01:27:15 +000032 >>> d = p._asdict() # convert to a dictionary
Guido van Rossum8ce8a782007-11-01 19:42:39 +000033 >>> d['x']
34 11
35 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +000036 Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +000037 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +000039
40 """
41
Christian Heimes2380ac72008-01-09 00:17:24 +000042 # Parse and validate the field names. Validation serves two purposes,
43 # generating informative error messages and preventing template injection attacks.
Guido van Rossum8ce8a782007-11-01 19:42:39 +000044 if isinstance(field_names, str):
45 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
46 field_names = tuple(field_names)
47 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +000048 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +000049 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
50 if _iskeyword(name):
51 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
52 if name[0].isdigit():
53 raise ValueError('Type names and field names cannot start with a number: %r' % name)
54 seen_names = set()
55 for name in field_names:
Christian Heimes0449f632007-12-15 01:27:15 +000056 if name.startswith('_'):
57 raise ValueError('Field names cannot start with an underscore: %r' % name)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000058 if name in seen_names:
59 raise ValueError('Encountered duplicate field name: %r' % name)
60 seen_names.add(name)
61
62 # Create and fill-in the class template
Christian Heimesfaf2f632008-01-06 16:59:19 +000063 numfields = len(field_names)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000064 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Guido van Rossumd59da4b2007-05-22 18:11:13 +000065 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
Christian Heimes99170a52007-12-19 02:07:34 +000066 dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
Guido van Rossumd59da4b2007-05-22 18:11:13 +000067 template = '''class %(typename)s(tuple):
Christian Heimes0449f632007-12-15 01:27:15 +000068 '%(typename)s(%(argtxt)s)' \n
69 __slots__ = () \n
Christian Heimesfaf2f632008-01-06 16:59:19 +000070 _fields = %(field_names)r \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +000071 def __new__(cls, %(argtxt)s):
Christian Heimes0449f632007-12-15 01:27:15 +000072 return tuple.__new__(cls, (%(argtxt)s)) \n
Christian Heimesfaf2f632008-01-06 16:59:19 +000073 @classmethod
Christian Heimes043d6f62008-01-07 17:19:16 +000074 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +000075 'Make a new %(typename)s object from a sequence or iterable'
Christian Heimes043d6f62008-01-07 17:19:16 +000076 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +000077 if len(result) != %(numfields)d:
78 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
79 return result \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +000080 def __repr__(self):
Christian Heimes0449f632007-12-15 01:27:15 +000081 return '%(typename)s(%(reprtxt)s)' %% self \n
Christian Heimes99170a52007-12-19 02:07:34 +000082 def _asdict(t):
Christian Heimes0449f632007-12-15 01:27:15 +000083 'Return a new dict which maps field names to their values'
Christian Heimes99170a52007-12-19 02:07:34 +000084 return {%(dicttxt)s} \n
Christian Heimes0449f632007-12-15 01:27:15 +000085 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +000086 'Return a new %(typename)s object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +000087 result = self._make(map(kwds.pop, %(field_names)r, self))
88 if kwds:
89 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
90 return result \n\n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +000091 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000092 template += ' %s = property(itemgetter(%d))\n' % (name, i)
93 if verbose:
94 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000095
96 # Execute the template string in a temporary namespace
Christian Heimes99170a52007-12-19 02:07:34 +000097 namespace = dict(itemgetter=_itemgetter)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000098 try:
99 exec(template, namespace)
100 except SyntaxError as e:
Christian Heimes99170a52007-12-19 02:07:34 +0000101 raise SyntaxError(e.msg + ':\n' + template) from e
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000102 result = namespace[typename]
103
104 # For pickling to work, the __module__ variable needs to be set to the frame
105 # where the named tuple is created. Bypass this step in enviroments where
106 # sys._getframe is not defined (Jython for example).
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000107 if hasattr(_sys, '_getframe'):
108 result.__module__ = _sys._getframe(1).f_globals['__name__']
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000109
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000110 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112
Guido van Rossumd8faa362007-04-27 19:54:29 +0000113
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000114################################################################################
115### UserDict
116################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000118class UserDict(MutableMapping):
119
120 # Start by filling-out the abstract methods
121 def __init__(self, dict=None, **kwargs):
122 self.data = {}
123 if dict is not None:
124 self.update(dict)
125 if len(kwargs):
126 self.update(kwargs)
127 def __len__(self): return len(self.data)
128 def __getitem__(self, key):
129 if key in self.data:
130 return self.data[key]
131 if hasattr(self.__class__, "__missing__"):
132 return self.__class__.__missing__(self, key)
133 raise KeyError(key)
134 def __setitem__(self, key, item): self.data[key] = item
135 def __delitem__(self, key): del self.data[key]
136 def __iter__(self):
137 return iter(self.data)
138
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000139 # Modify __contains__ to work correctly when __missing__ is present
140 def __contains__(self, key):
141 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000142
143 # Now, add the methods in dicts but not in MutableMapping
144 def __repr__(self): return repr(self.data)
145 def copy(self):
146 if self.__class__ is UserDict:
147 return UserDict(self.data.copy())
148 import copy
149 data = self.data
150 try:
151 self.data = {}
152 c = copy.copy(self)
153 finally:
154 self.data = data
155 c.update(self)
156 return c
157 @classmethod
158 def fromkeys(cls, iterable, value=None):
159 d = cls()
160 for key in iterable:
161 d[key] = value
162 return d
163
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000164
165
166################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000167### UserList
168################################################################################
169
170class UserList(MutableSequence):
171 """A more or less complete user-defined wrapper around list objects."""
172 def __init__(self, initlist=None):
173 self.data = []
174 if initlist is not None:
175 # XXX should this accept an arbitrary sequence?
176 if type(initlist) == type(self.data):
177 self.data[:] = initlist
178 elif isinstance(initlist, UserList):
179 self.data[:] = initlist.data[:]
180 else:
181 self.data = list(initlist)
182 def __repr__(self): return repr(self.data)
183 def __lt__(self, other): return self.data < self.__cast(other)
184 def __le__(self, other): return self.data <= self.__cast(other)
185 def __eq__(self, other): return self.data == self.__cast(other)
186 def __ne__(self, other): return self.data != self.__cast(other)
187 def __gt__(self, other): return self.data > self.__cast(other)
188 def __ge__(self, other): return self.data >= self.__cast(other)
189 def __cast(self, other):
190 return other.data if isinstance(other, UserList) else other
191 def __cmp__(self, other):
192 return cmp(self.data, self.__cast(other))
193 def __contains__(self, item): return item in self.data
194 def __len__(self): return len(self.data)
195 def __getitem__(self, i): return self.data[i]
196 def __setitem__(self, i, item): self.data[i] = item
197 def __delitem__(self, i): del self.data[i]
198 def __add__(self, other):
199 if isinstance(other, UserList):
200 return self.__class__(self.data + other.data)
201 elif isinstance(other, type(self.data)):
202 return self.__class__(self.data + other)
203 return self.__class__(self.data + list(other))
204 def __radd__(self, other):
205 if isinstance(other, UserList):
206 return self.__class__(other.data + self.data)
207 elif isinstance(other, type(self.data)):
208 return self.__class__(other + self.data)
209 return self.__class__(list(other) + self.data)
210 def __iadd__(self, other):
211 if isinstance(other, UserList):
212 self.data += other.data
213 elif isinstance(other, type(self.data)):
214 self.data += other
215 else:
216 self.data += list(other)
217 return self
218 def __mul__(self, n):
219 return self.__class__(self.data*n)
220 __rmul__ = __mul__
221 def __imul__(self, n):
222 self.data *= n
223 return self
224 def append(self, item): self.data.append(item)
225 def insert(self, i, item): self.data.insert(i, item)
226 def pop(self, i=-1): return self.data.pop(i)
227 def remove(self, item): self.data.remove(item)
228 def count(self, item): return self.data.count(item)
229 def index(self, item, *args): return self.data.index(item, *args)
230 def reverse(self): self.data.reverse()
231 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
232 def extend(self, other):
233 if isinstance(other, UserList):
234 self.data.extend(other.data)
235 else:
236 self.data.extend(other)
237
238
239
240################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000241### UserString
242################################################################################
243
244class UserString(Sequence):
245 def __init__(self, seq):
246 if isinstance(seq, str):
247 self.data = seq
248 elif isinstance(seq, UserString):
249 self.data = seq.data[:]
250 else:
251 self.data = str(seq)
252 def __str__(self): return str(self.data)
253 def __repr__(self): return repr(self.data)
254 def __int__(self): return int(self.data)
255 def __long__(self): return int(self.data)
256 def __float__(self): return float(self.data)
257 def __complex__(self): return complex(self.data)
258 def __hash__(self): return hash(self.data)
259
260 def __eq__(self, string):
261 if isinstance(string, UserString):
262 return self.data == string.data
263 return self.data == string
264 def __ne__(self, string):
265 if isinstance(string, UserString):
266 return self.data != string.data
267 return self.data != string
268 def __lt__(self, string):
269 if isinstance(string, UserString):
270 return self.data < string.data
271 return self.data < string
272 def __le__(self, string):
273 if isinstance(string, UserString):
274 return self.data <= string.data
275 return self.data <= string
276 def __gt__(self, string):
277 if isinstance(string, UserString):
278 return self.data > string.data
279 return self.data > string
280 def __ge__(self, string):
281 if isinstance(string, UserString):
282 return self.data >= string.data
283 return self.data >= string
284
285 def __contains__(self, char):
286 if isinstance(char, UserString):
287 char = char.data
288 return char in self.data
289
290 def __len__(self): return len(self.data)
291 def __getitem__(self, index): return self.__class__(self.data[index])
292 def __add__(self, other):
293 if isinstance(other, UserString):
294 return self.__class__(self.data + other.data)
295 elif isinstance(other, str):
296 return self.__class__(self.data + other)
297 return self.__class__(self.data + str(other))
298 def __radd__(self, other):
299 if isinstance(other, str):
300 return self.__class__(other + self.data)
301 return self.__class__(str(other) + self.data)
302 def __mul__(self, n):
303 return self.__class__(self.data*n)
304 __rmul__ = __mul__
305 def __mod__(self, args):
306 return self.__class__(self.data % args)
307
308 # the following methods are defined in alphabetical order:
309 def capitalize(self): return self.__class__(self.data.capitalize())
310 def center(self, width, *args):
311 return self.__class__(self.data.center(width, *args))
312 def count(self, sub, start=0, end=_sys.maxsize):
313 if isinstance(sub, UserString):
314 sub = sub.data
315 return self.data.count(sub, start, end)
316 def encode(self, encoding=None, errors=None): # XXX improve this?
317 if encoding:
318 if errors:
319 return self.__class__(self.data.encode(encoding, errors))
320 return self.__class__(self.data.encode(encoding))
321 return self.__class__(self.data.encode())
322 def endswith(self, suffix, start=0, end=_sys.maxsize):
323 return self.data.endswith(suffix, start, end)
324 def expandtabs(self, tabsize=8):
325 return self.__class__(self.data.expandtabs(tabsize))
326 def find(self, sub, start=0, end=_sys.maxsize):
327 if isinstance(sub, UserString):
328 sub = sub.data
329 return self.data.find(sub, start, end)
330 def format(self, *args, **kwds):
331 return self.data.format(*args, **kwds)
332 def index(self, sub, start=0, end=_sys.maxsize):
333 return self.data.index(sub, start, end)
334 def isalpha(self): return self.data.isalpha()
335 def isalnum(self): return self.data.isalnum()
336 def isdecimal(self): return self.data.isdecimal()
337 def isdigit(self): return self.data.isdigit()
338 def isidentifier(self): return self.data.isidentifier()
339 def islower(self): return self.data.islower()
340 def isnumeric(self): return self.data.isnumeric()
341 def isspace(self): return self.data.isspace()
342 def istitle(self): return self.data.istitle()
343 def isupper(self): return self.data.isupper()
344 def join(self, seq): return self.data.join(seq)
345 def ljust(self, width, *args):
346 return self.__class__(self.data.ljust(width, *args))
347 def lower(self): return self.__class__(self.data.lower())
348 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
349 def partition(self, sep):
350 return self.data.partition(sep)
351 def replace(self, old, new, maxsplit=-1):
352 if isinstance(old, UserString):
353 old = old.data
354 if isinstance(new, UserString):
355 new = new.data
356 return self.__class__(self.data.replace(old, new, maxsplit))
357 def rfind(self, sub, start=0, end=_sys.maxsize):
358 return self.data.rfind(sub, start, end)
359 def rindex(self, sub, start=0, end=_sys.maxsize):
360 return self.data.rindex(sub, start, end)
361 def rjust(self, width, *args):
362 return self.__class__(self.data.rjust(width, *args))
363 def rpartition(self, sep):
364 return self.data.rpartition(sep)
365 def rstrip(self, chars=None):
366 return self.__class__(self.data.rstrip(chars))
367 def split(self, sep=None, maxsplit=-1):
368 return self.data.split(sep, maxsplit)
369 def rsplit(self, sep=None, maxsplit=-1):
370 return self.data.rsplit(sep, maxsplit)
371 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
372 def startswith(self, prefix, start=0, end=_sys.maxsize):
373 return self.data.startswith(prefix, start, end)
374 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
375 def swapcase(self): return self.__class__(self.data.swapcase())
376 def title(self): return self.__class__(self.data.title())
377 def translate(self, *args):
378 return self.__class__(self.data.translate(*args))
379 def upper(self): return self.__class__(self.data.upper())
380 def zfill(self, width): return self.__class__(self.data.zfill(width))
381
382
383
384################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000385### Simple tests
386################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000387
388if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000389 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000390 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000391 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000392 p = Point(x=10, y=20)
393 assert p == loads(dumps(p))
394
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000395 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000396 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000397 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000398 @property
399 def hypot(self):
400 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000401 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000402 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000403
Christian Heimes25bb7832008-01-11 16:17:00 +0000404 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000405 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000406
407 class Point(namedtuple('Point', 'x y')):
408 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000409 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000410 _make = classmethod(tuple.__new__)
411 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000412 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000413
414 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000415
Christian Heimes25bb7832008-01-11 16:17:00 +0000416 Point3D = namedtuple('Point3D', Point._fields + ('z',))
417 print(Point3D.__doc__)
418
Guido van Rossumd8faa362007-04-27 19:54:29 +0000419 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000420 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000421 print(TestResults(*doctest.testmod()))