Local stack. This class works similar to a :class:`Local` but keeps a stack of objects instead. This is best explained with an example:: >>> ls = LocalStack() >>> ls.push(42) >>> ls.top 42 >>> ls.push(23) >>> ls.top 23 >>> ls
| 153 | |
| 154 | |
| 155 | class _LocalStack: |
| 156 | class="st">"""Local stack. |
| 157 | |
| 158 | This class works similar to a :class:`Local` but keeps a stack |
| 159 | of objects instead. This is best explained with an example:: |
| 160 | |
| 161 | >>> ls = LocalStack() |
| 162 | >>> ls.push(42) |
| 163 | >>> ls.top |
| 164 | 42 |
| 165 | >>> ls.push(23) |
| 166 | >>> ls.top |
| 167 | 23 |
| 168 | >>> ls.pop() |
| 169 | 23 |
| 170 | >>> ls.top |
| 171 | 42 |
| 172 | |
| 173 | They can be force released by using a :class:`LocalManager` or with |
| 174 | the :func:`release_local` function but the correct way is to pop the |
| 175 | item from the stack after using. When the stack is empty it will |
| 176 | no longer be bound to the current context (and as such released). |
| 177 | |
| 178 | By calling the stack without arguments it will return a proxy that |
| 179 | resolves to the topmost item on the stack. |
| 180 | class="st">""" |
| 181 | |
| 182 | def __init__(self): |
| 183 | self._local = Local() |
| 184 | |
| 185 | def __release_local__(self): |
| 186 | self._local.__release_local__() |
| 187 | |
| 188 | def _get__ident_func__(self): |
| 189 | return self._local.__ident_func__ |
| 190 | |
| 191 | def _set__ident_func__(self, value): |
| 192 | object.__setattr__(self._local, &class="cm">#x27;__ident_func__', value) |
| 193 | __ident_func__ = property(_get__ident_func__, _set__ident_func__) |
| 194 | del _get__ident_func__, _set__ident_func__ |
| 195 | |
| 196 | def __call__(self): |
| 197 | def _lookup(): |
| 198 | rv = self.top |
| 199 | if rv is None: |
| 200 | raise RuntimeError(&class="cm">#x27;object unbound') |
| 201 | return rv |
| 202 | return Proxy(_lookup) |
| 203 | |
| 204 | def push(self, obj): |
| 205 | class="st">""class="st">"Push a new item to the stack."class="st">"" |
| 206 | rv = getattr(self._local, &class="cm">#x27;stack', None) |
| 207 | if rv is None: |
| 208 | class="cm"># pylint: disable=assigning-non-slot |
| 209 | class="cm"># This attribute is defined now. |
| 210 | self._local.stack = rv = [] |
| 211 | rv.append(obj) |
| 212 | return rv |