PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/django-1.5/django/utils/datastructures.py

https://github.com/theosp/google_appengine
Python | 518 lines | 515 code | 2 blank | 1 comment | 1 complexity | 7d64e58ef2eb73fc13da71b8f9a27fd0 MD5 | raw file
  1. import copy
  2. import warnings
  3. from django.utils import six
  4. class MergeDict(object):
  5. """
  6. A simple class for creating new "virtual" dictionaries that actually look
  7. up values in more than one dictionary, passed in the constructor.
  8. If a key appears in more than one of the given dictionaries, only the
  9. first occurrence will be used.
  10. """
  11. def __init__(self, *dicts):
  12. self.dicts = dicts
  13. def __getitem__(self, key):
  14. for dict_ in self.dicts:
  15. try:
  16. return dict_[key]
  17. except KeyError:
  18. pass
  19. raise KeyError
  20. def __copy__(self):
  21. return self.__class__(*self.dicts)
  22. def get(self, key, default=None):
  23. try:
  24. return self[key]
  25. except KeyError:
  26. return default
  27. # This is used by MergeDicts of MultiValueDicts.
  28. def getlist(self, key):
  29. for dict_ in self.dicts:
  30. if key in dict_:
  31. return dict_.getlist(key)
  32. return []
  33. def _iteritems(self):
  34. seen = set()
  35. for dict_ in self.dicts:
  36. for item in six.iteritems(dict_):
  37. k = item[0]
  38. if k in seen:
  39. continue
  40. seen.add(k)
  41. yield item
  42. def _iterkeys(self):
  43. for k, v in self._iteritems():
  44. yield k
  45. def _itervalues(self):
  46. for k, v in self._iteritems():
  47. yield v
  48. if six.PY3:
  49. items = _iteritems
  50. keys = _iterkeys
  51. values = _itervalues
  52. else:
  53. iteritems = _iteritems
  54. iterkeys = _iterkeys
  55. itervalues = _itervalues
  56. def items(self):
  57. return list(self.iteritems())
  58. def keys(self):
  59. return list(self.iterkeys())
  60. def values(self):
  61. return list(self.itervalues())
  62. def has_key(self, key):
  63. for dict_ in self.dicts:
  64. if key in dict_:
  65. return True
  66. return False
  67. __contains__ = has_key
  68. __iter__ = _iterkeys
  69. def copy(self):
  70. """Returns a copy of this object."""
  71. return self.__copy__()
  72. def __str__(self):
  73. '''
  74. Returns something like
  75. "{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}"
  76. instead of the generic "<object meta-data>" inherited from object.
  77. '''
  78. return str(dict(self.items()))
  79. def __repr__(self):
  80. '''
  81. Returns something like
  82. MergeDict({'key1': 'val1', 'key2': 'val2'}, {'key3': 'val3'})
  83. instead of generic "<object meta-data>" inherited from object.
  84. '''
  85. dictreprs = ', '.join(repr(d) for d in self.dicts)
  86. return '%s(%s)' % (self.__class__.__name__, dictreprs)
  87. class SortedDict(dict):
  88. """
  89. A dictionary that keeps its keys in the order in which they're inserted.
  90. """
  91. def __new__(cls, *args, **kwargs):
  92. instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
  93. instance.keyOrder = []
  94. return instance
  95. def __init__(self, data=None):
  96. if data is None or isinstance(data, dict):
  97. data = data or []
  98. super(SortedDict, self).__init__(data)
  99. self.keyOrder = list(data) if data else []
  100. else:
  101. super(SortedDict, self).__init__()
  102. super_set = super(SortedDict, self).__setitem__
  103. for key, value in data:
  104. # Take the ordering from first key
  105. if key not in self:
  106. self.keyOrder.append(key)
  107. # But override with last value in data (dict() does this)
  108. super_set(key, value)
  109. def __deepcopy__(self, memo):
  110. return self.__class__([(key, copy.deepcopy(value, memo))
  111. for key, value in self.items()])
  112. def __copy__(self):
  113. # The Python's default copy implementation will alter the state
  114. # of self. The reason for this seems complex but is likely related to
  115. # subclassing dict.
  116. return self.copy()
  117. def __setitem__(self, key, value):
  118. if key not in self:
  119. self.keyOrder.append(key)
  120. super(SortedDict, self).__setitem__(key, value)
  121. def __delitem__(self, key):
  122. super(SortedDict, self).__delitem__(key)
  123. self.keyOrder.remove(key)
  124. def __iter__(self):
  125. return iter(self.keyOrder)
  126. def __reversed__(self):
  127. return reversed(self.keyOrder)
  128. def pop(self, k, *args):
  129. result = super(SortedDict, self).pop(k, *args)
  130. try:
  131. self.keyOrder.remove(k)
  132. except ValueError:
  133. # Key wasn't in the dictionary in the first place. No problem.
  134. pass
  135. return result
  136. def popitem(self):
  137. result = super(SortedDict, self).popitem()
  138. self.keyOrder.remove(result[0])
  139. return result
  140. def _iteritems(self):
  141. for key in self.keyOrder:
  142. yield key, self[key]
  143. def _iterkeys(self):
  144. for key in self.keyOrder:
  145. yield key
  146. def _itervalues(self):
  147. for key in self.keyOrder:
  148. yield self[key]
  149. if six.PY3:
  150. items = _iteritems
  151. keys = _iterkeys
  152. values = _itervalues
  153. else:
  154. iteritems = _iteritems
  155. iterkeys = _iterkeys
  156. itervalues = _itervalues
  157. def items(self):
  158. return [(k, self[k]) for k in self.keyOrder]
  159. def keys(self):
  160. return self.keyOrder[:]
  161. def values(self):
  162. return [self[k] for k in self.keyOrder]
  163. def update(self, dict_):
  164. for k, v in six.iteritems(dict_):
  165. self[k] = v
  166. def setdefault(self, key, default):
  167. if key not in self:
  168. self.keyOrder.append(key)
  169. return super(SortedDict, self).setdefault(key, default)
  170. def value_for_index(self, index):
  171. """Returns the value of the item at the given zero-based index."""
  172. # This, and insert() are deprecated because they cannot be implemented
  173. # using collections.OrderedDict (Python 2.7 and up), which we'll
  174. # eventually switch to
  175. warnings.warn(
  176. "SortedDict.value_for_index is deprecated", PendingDeprecationWarning,
  177. stacklevel=2
  178. )
  179. return self[self.keyOrder[index]]
  180. def insert(self, index, key, value):
  181. """Inserts the key, value pair before the item with the given index."""
  182. warnings.warn(
  183. "SortedDict.insert is deprecated", PendingDeprecationWarning,
  184. stacklevel=2
  185. )
  186. if key in self.keyOrder:
  187. n = self.keyOrder.index(key)
  188. del self.keyOrder[n]
  189. if n < index:
  190. index -= 1
  191. self.keyOrder.insert(index, key)
  192. super(SortedDict, self).__setitem__(key, value)
  193. def copy(self):
  194. """Returns a copy of this object."""
  195. # This way of initializing the copy means it works for subclasses, too.
  196. return self.__class__(self)
  197. def __repr__(self):
  198. """
  199. Replaces the normal dict.__repr__ with a version that returns the keys
  200. in their sorted order.
  201. """
  202. return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in six.iteritems(self)])
  203. def clear(self):
  204. super(SortedDict, self).clear()
  205. self.keyOrder = []
  206. class MultiValueDictKeyError(KeyError):
  207. pass
  208. class MultiValueDict(dict):
  209. """
  210. A subclass of dictionary customized to handle multiple values for the
  211. same key.
  212. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
  213. >>> d['name']
  214. 'Simon'
  215. >>> d.getlist('name')
  216. ['Adrian', 'Simon']
  217. >>> d.getlist('doesnotexist')
  218. []
  219. >>> d.getlist('doesnotexist', ['Adrian', 'Simon'])
  220. ['Adrian', 'Simon']
  221. >>> d.get('lastname', 'nonexistent')
  222. 'nonexistent'
  223. >>> d.setlist('lastname', ['Holovaty', 'Willison'])
  224. This class exists to solve the irritating problem raised by cgi.parse_qs,
  225. which returns a list for every key, even though most Web forms submit
  226. single name-value pairs.
  227. """
  228. def __init__(self, key_to_list_mapping=()):
  229. super(MultiValueDict, self).__init__(key_to_list_mapping)
  230. def __repr__(self):
  231. return "<%s: %s>" % (self.__class__.__name__,
  232. super(MultiValueDict, self).__repr__())
  233. def __getitem__(self, key):
  234. """
  235. Returns the last data value for this key, or [] if it's an empty list;
  236. raises KeyError if not found.
  237. """
  238. try:
  239. list_ = super(MultiValueDict, self).__getitem__(key)
  240. except KeyError:
  241. raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
  242. try:
  243. return list_[-1]
  244. except IndexError:
  245. return []
  246. def __setitem__(self, key, value):
  247. super(MultiValueDict, self).__setitem__(key, [value])
  248. def __copy__(self):
  249. return self.__class__([
  250. (k, v[:])
  251. for k, v in self.lists()
  252. ])
  253. def __deepcopy__(self, memo=None):
  254. if memo is None:
  255. memo = {}
  256. result = self.__class__()
  257. memo[id(self)] = result
  258. for key, value in dict.items(self):
  259. dict.__setitem__(result, copy.deepcopy(key, memo),
  260. copy.deepcopy(value, memo))
  261. return result
  262. def __getstate__(self):
  263. obj_dict = self.__dict__.copy()
  264. obj_dict['_data'] = dict([(k, self.getlist(k)) for k in self])
  265. return obj_dict
  266. def __setstate__(self, obj_dict):
  267. data = obj_dict.pop('_data', {})
  268. for k, v in data.items():
  269. self.setlist(k, v)
  270. self.__dict__.update(obj_dict)
  271. def get(self, key, default=None):
  272. """
  273. Returns the last data value for the passed key. If key doesn't exist
  274. or value is an empty list, then default is returned.
  275. """
  276. try:
  277. val = self[key]
  278. except KeyError:
  279. return default
  280. if val == []:
  281. return default
  282. return val
  283. def getlist(self, key, default=None):
  284. """
  285. Returns the list of values for the passed key. If key doesn't exist,
  286. then a default value is returned.
  287. """
  288. try:
  289. return super(MultiValueDict, self).__getitem__(key)
  290. except KeyError:
  291. if default is None:
  292. return []
  293. return default
  294. def setlist(self, key, list_):
  295. super(MultiValueDict, self).__setitem__(key, list_)
  296. def setdefault(self, key, default=None):
  297. if key not in self:
  298. self[key] = default
  299. # Do not return default here because __setitem__() may store
  300. # another value -- QueryDict.__setitem__() does. Look it up.
  301. return self[key]
  302. def setlistdefault(self, key, default_list=None):
  303. if key not in self:
  304. if default_list is None:
  305. default_list = []
  306. self.setlist(key, default_list)
  307. # Do not return default_list here because setlist() may store
  308. # another value -- QueryDict.setlist() does. Look it up.
  309. return self.getlist(key)
  310. def appendlist(self, key, value):
  311. """Appends an item to the internal list associated with key."""
  312. self.setlistdefault(key).append(value)
  313. def _iteritems(self):
  314. """
  315. Yields (key, value) pairs, where value is the last item in the list
  316. associated with the key.
  317. """
  318. for key in self:
  319. yield key, self[key]
  320. def _iterlists(self):
  321. """Yields (key, list) pairs."""
  322. return six.iteritems(super(MultiValueDict, self))
  323. def _itervalues(self):
  324. """Yield the last value on every key list."""
  325. for key in self:
  326. yield self[key]
  327. if six.PY3:
  328. items = _iteritems
  329. lists = _iterlists
  330. values = _itervalues
  331. else:
  332. iteritems = _iteritems
  333. iterlists = _iterlists
  334. itervalues = _itervalues
  335. def items(self):
  336. return list(self.iteritems())
  337. def lists(self):
  338. return list(self.iterlists())
  339. def values(self):
  340. return list(self.itervalues())
  341. def copy(self):
  342. """Returns a shallow copy of this object."""
  343. return copy.copy(self)
  344. def update(self, *args, **kwargs):
  345. """
  346. update() extends rather than replaces existing key lists.
  347. Also accepts keyword args.
  348. """
  349. if len(args) > 1:
  350. raise TypeError("update expected at most 1 arguments, got %d" % len(args))
  351. if args:
  352. other_dict = args[0]
  353. if isinstance(other_dict, MultiValueDict):
  354. for key, value_list in other_dict.lists():
  355. self.setlistdefault(key).extend(value_list)
  356. else:
  357. try:
  358. for key, value in other_dict.items():
  359. self.setlistdefault(key).append(value)
  360. except TypeError:
  361. raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary")
  362. for key, value in six.iteritems(kwargs):
  363. self.setlistdefault(key).append(value)
  364. def dict(self):
  365. """
  366. Returns current object as a dict with singular values.
  367. """
  368. return dict((key, self[key]) for key in self)
  369. class ImmutableList(tuple):
  370. """
  371. A tuple-like object that raises useful errors when it is asked to mutate.
  372. Example::
  373. >>> a = ImmutableList(range(5), warning="You cannot mutate this.")
  374. >>> a[3] = '4'
  375. Traceback (most recent call last):
  376. ...
  377. AttributeError: You cannot mutate this.
  378. """
  379. def __new__(cls, *args, **kwargs):
  380. if 'warning' in kwargs:
  381. warning = kwargs['warning']
  382. del kwargs['warning']
  383. else:
  384. warning = 'ImmutableList object is immutable.'
  385. self = tuple.__new__(cls, *args, **kwargs)
  386. self.warning = warning
  387. return self
  388. def complain(self, *wargs, **kwargs):
  389. if isinstance(self.warning, Exception):
  390. raise self.warning
  391. else:
  392. raise AttributeError(self.warning)
  393. # All list mutation functions complain.
  394. __delitem__ = complain
  395. __delslice__ = complain
  396. __iadd__ = complain
  397. __imul__ = complain
  398. __setitem__ = complain
  399. __setslice__ = complain
  400. append = complain
  401. extend = complain
  402. insert = complain
  403. pop = complain
  404. remove = complain
  405. sort = complain
  406. reverse = complain
  407. class DictWrapper(dict):
  408. """
  409. Wraps accesses to a dictionary so that certain values (those starting with
  410. the specified prefix) are passed through a function before being returned.
  411. The prefix is removed before looking up the real value.
  412. Used by the SQL construction code to ensure that values are correctly
  413. quoted before being used.
  414. """
  415. def __init__(self, data, func, prefix):
  416. super(DictWrapper, self).__init__(data)
  417. self.func = func
  418. self.prefix = prefix
  419. def __getitem__(self, key):
  420. """
  421. Retrieves the real value after stripping the prefix string (if
  422. present). If the prefix is present, pass the value through self.func
  423. before returning, otherwise return the raw value.
  424. """
  425. if key.startswith(self.prefix):
  426. use_func = True
  427. key = key[len(self.prefix):]
  428. else:
  429. use_func = False
  430. value = super(DictWrapper, self).__getitem__(key)
  431. if use_func:
  432. return self.func(value)
  433. return value