Ticket #13812: 13812_faster_context_using_deque.diff
File 13812_faster_context_using_deque.diff, 2.6 KB (added by , 14 years ago) |
---|
-
context.py
1 import collections 2 1 3 from django.core.exceptions import ImproperlyConfigured 2 4 from django.utils.importlib import import_module 3 5 … … 15 17 class BaseContext(object): 16 18 def __init__(self, dict_=None): 17 19 dict_ = dict_ or {} 18 self.dicts = [dict_]20 self.dicts = collections.deque((dict_,)) 19 21 20 22 def __repr__(self): 21 23 return repr(self.dicts) 22 24 23 25 def __iter__(self): 24 for d in reversed(self.dicts):26 for d in self.dicts: 25 27 yield d 26 28 27 29 def push(self): 28 30 d = {} 29 self.dicts.append (d)31 self.dicts.appendleft(d) 30 32 return d 31 33 32 34 def pop(self): 33 35 if len(self.dicts) == 1: 34 36 raise ContextPopException 35 return self.dicts.pop ()37 return self.dicts.popleft() 36 38 37 39 def __setitem__(self, key, value): 38 40 "Set a variable in the current context" 39 self.dicts[ -1][key] = value41 self.dicts[0][key] = value 40 42 41 43 def __getitem__(self, key): 42 44 "Get a variable's value, starting at the current context and going upward" 43 for d in reversed(self.dicts):45 for d in self.dicts: 44 46 if key in d: 45 47 return d[key] 46 48 raise KeyError(key) 47 49 48 50 def __delitem__(self, key): 49 51 "Delete a variable from the current context" 50 del self.dicts[ -1][key]52 del self.dicts[0][key] 51 53 52 54 def has_key(self, key): 53 55 for d in self.dicts: … … 59 61 return self.has_key(key) 60 62 61 63 def get(self, key, otherwise=None): 62 for d in reversed(self.dicts):64 for d in self.dicts: 63 65 if key in d: 64 66 return d[key] 65 67 return otherwise … … 76 78 "Like dict.update(). Pushes an entire dictionary's keys and values onto the context." 77 79 if not hasattr(other_dict, '__getitem__'): 78 80 raise TypeError('other_dict must be a mapping (dictionary-like) object.') 79 self.dicts.append (other_dict)81 self.dicts.appendleft(other_dict) 80 82 return other_dict 81 83 82 84 class RenderContext(BaseContext): … … 95 97 template context. 96 98 """ 97 99 def __iter__(self): 98 for d in self.dicts[ -1]:100 for d in self.dicts[0]: 99 101 yield d 100 102 101 103 def has_key(self, key): 102 return key in self.dicts[ -1]104 return key in self.dicts[0] 103 105 104 106 def get(self, key, otherwise=None): 105 d = self.dicts[ -1]107 d = self.dicts[0] 106 108 if key in d: 107 109 return d[key] 108 110 return otherwise