urwidtrees 1.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
urwidtrees/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ from .tree import Tree, SimpleTree
2
+ from .decoration import DecoratedTree, CollapsibleTree
3
+ from .decoration import IndentedTree, CollapsibleIndentedTree
4
+ from .decoration import ArrowTree, CollapsibleArrowTree
5
+ from .nested import NestedTree
6
+ from .widgets import TreeBox
7
+
8
+ from .version import __version__
@@ -0,0 +1,509 @@
1
+ # Copyright (C) 2013 Patrick Totzke <patricktotzke@gmail.com>
2
+ # This file is released under the GNU GPL, version 3 or a later revision.
3
+ import urwid
4
+
5
+ from .tree import Tree, SimpleTree
6
+
7
+
8
+ class NoSpaceError(Exception):
9
+ """too little space for requested decoration"""
10
+
11
+
12
+ class DecoratedTree(Tree):
13
+ """
14
+ :class:`Tree` that wraps around another :class:`Tree` and allows to read
15
+ original content as well as decorated versions thereof.
16
+ """
17
+ def __init__(self, content):
18
+ if not isinstance(content, Tree):
19
+ # do we need this?
20
+ content = SimpleTree(content)
21
+ self._tree = content
22
+ self.root = self._tree.root
23
+
24
+ def get_decorated(self, pos):
25
+ """
26
+ return widget that consists of the content of original tree at given
27
+ position plus its decoration.
28
+ """
29
+ return self.decorate(pos, self[pos])
30
+
31
+ def decorate(self, pos, widget, is_first=True):
32
+ """
33
+ decorate `widget` according to a position `pos` in the original tree.
34
+ setting `is_first` to False indicates that we are decorating a line
35
+ that is *part* of the (multi-line) content at this position, but not
36
+ the first part. This allows to omit incoming arrow heads for example.
37
+ """
38
+ return widget
39
+
40
+ # pass on everything else to the original tree.
41
+
42
+ def parent_position(self, pos):
43
+ return self._tree.parent_position(pos)
44
+
45
+ def first_child_position(self, pos):
46
+ return self._tree.first_child_position(pos)
47
+
48
+ def last_child_position(self, pos):
49
+ return self._tree.last_child_position(pos)
50
+
51
+ def next_sibling_position(self, pos):
52
+ return self._tree.next_sibling_position(pos)
53
+
54
+ def prev_sibling_position(self, pos):
55
+ return self._tree.prev_sibling_position(pos)
56
+
57
+ def __getitem__(self, pos):
58
+ return self._tree[pos]
59
+
60
+
61
+ class CollapseMixin(object):
62
+ """
63
+ Mixin for :class:`Tree` that allows to collapse subtrees.
64
+
65
+ This works by overwriting
66
+ :meth:`[first|last]_child_position <first_child_position>`, forcing them to
67
+ return `None` if the given position is considered collapsed. We use a
68
+ (given) callable `is_collapsed` that accepts positions and returns a
69
+ boolean to determine which node is considered collapsed.
70
+ """
71
+ def __init__(self, is_collapsed=lambda pos: False,
72
+ **kwargs):
73
+ self._initially_collapsed = is_collapsed
74
+ self._divergent_positions = []
75
+
76
+ def is_collapsed(self, pos):
77
+ """checks if given position is currently collapsed"""
78
+ collapsed = self._initially_collapsed(pos)
79
+ if pos in self._divergent_positions:
80
+ collapsed = not collapsed
81
+ return collapsed
82
+
83
+ # implement functionality by overwriting local position transformations
84
+
85
+ # TODO: ATM this assumes we are in a wrapper: it uses self._tree.
86
+ # This is not necessarily true, for example for subclasses of SimpleTree!
87
+ # maybe define this whole class as a wrapper?
88
+
89
+ def last_child_position(self, pos):
90
+ if self.is_collapsed(pos):
91
+ return None
92
+ return self._tree.last_child_position(pos)
93
+
94
+ def first_child_position(self, pos):
95
+ if self.is_collapsed(pos):
96
+ return None
97
+ return self._tree.first_child_position(pos)
98
+
99
+ def collapsible(self, pos):
100
+ return not self._tree.is_leaf(pos)
101
+
102
+ def set_position_collapsed(self, pos, is_collapsed):
103
+ if self.collapsible(pos):
104
+ if self._initially_collapsed(pos) == is_collapsed:
105
+ if pos in self._divergent_positions:
106
+ self._divergent_positions.remove(pos)
107
+ else:
108
+ if pos not in self._divergent_positions:
109
+ self._divergent_positions.append(pos)
110
+
111
+ def toggle_collapsed(self, pos):
112
+ self.set_position_collapsed(pos, not self.is_collapsed(pos))
113
+
114
+ def collapse(self, pos):
115
+ self.set_position_collapsed(pos, True)
116
+
117
+ def collapse_all(self):
118
+ self.set_collapsed_all(True)
119
+
120
+ def expand_all(self):
121
+ self.set_collapsed_all(False)
122
+
123
+ def set_collapsed_all(self, is_collapsed):
124
+ self._initially_collapsed = lambda x: is_collapsed
125
+ self._divergent_positions = []
126
+
127
+ def expand(self, pos):
128
+ self.set_position_collapsed(pos, False)
129
+
130
+
131
+ class CollapseIconMixin(CollapseMixin):
132
+ """
133
+ Mixin for :class:`Tree` that allows to collapse subtrees and use
134
+ an indicator icon in line decorations.
135
+ This Mixin adds the ability to construct collapse-icon for a
136
+ position, indicating its collapse status to :class:`CollapseMixin`.
137
+ """
138
+ def __init__(self,
139
+ is_collapsed=lambda pos: False,
140
+ icon_collapsed_char='+',
141
+ icon_expanded_char='-',
142
+ icon_collapsed_att=None,
143
+ icon_expanded_att=None,
144
+ icon_frame_left_char='[',
145
+ icon_frame_right_char=']',
146
+ icon_frame_att=None,
147
+ icon_focussed_att=None,
148
+ **kwargs):
149
+ """TODO: docstrings"""
150
+ CollapseMixin.__init__(self, is_collapsed, **kwargs)
151
+ self._icon_collapsed_char = icon_collapsed_char
152
+ self._icon_expanded_char = icon_expanded_char
153
+ self._icon_collapsed_att = icon_collapsed_att
154
+ self._icon_expanded_att = icon_expanded_att
155
+ self._icon_frame_left_char = icon_frame_left_char
156
+ self._icon_frame_right_char = icon_frame_right_char
157
+ self._icon_frame_att = icon_frame_att
158
+ self._icon_focussed_att = icon_focussed_att
159
+
160
+ def _construct_collapse_icon(self, pos):
161
+ width = 0
162
+ widget = None
163
+ char = self._icon_expanded_char
164
+ charatt = self._icon_expanded_att
165
+ if self.is_collapsed(pos):
166
+ char = self._icon_collapsed_char
167
+ charatt = self._icon_collapsed_att
168
+ if char is not None:
169
+
170
+ columns = []
171
+ if self._icon_frame_left_char is not None:
172
+ lchar = self._icon_frame_left_char
173
+ charlen = len(lchar)
174
+ leftframe = urwid.Text((self._icon_frame_att, lchar))
175
+ columns.append((charlen, leftframe))
176
+ width += charlen
177
+
178
+ # next we build out icon widget: we feed all markups to a Text,
179
+ # make it selectable (to toggle collapse) if requested
180
+ markup = (charatt, char)
181
+ widget = urwid.Text(markup)
182
+ charlen = len(char)
183
+ columns.append((charlen, widget))
184
+ width += charlen
185
+
186
+ if self._icon_frame_right_char is not None:
187
+ rchar = self._icon_frame_right_char
188
+ charlen = len(rchar)
189
+ rightframe = urwid.Text((self._icon_frame_att, rchar))
190
+ columns.append((charlen, rightframe))
191
+ width += charlen
192
+
193
+ widget = urwid.Columns(columns)
194
+ return width, widget
195
+
196
+
197
+ class CollapsibleTree(CollapseMixin, DecoratedTree):
198
+ """Undecorated Tree that allows to collapse subtrees"""
199
+ def __init__(self, tree, **kwargs):
200
+ DecoratedTree.__init__(self, tree)
201
+ CollapseMixin.__init__(self, **kwargs)
202
+
203
+
204
+ class IndentedTree(DecoratedTree):
205
+ """Indent tree nodes according to their depth in the tree"""
206
+ def __init__(self, tree, indent=2):
207
+ """
208
+ :param tree: tree of widgets to be displayed
209
+ :type tree: Tree
210
+ :param indent: indentation width
211
+ :type indent: int
212
+ """
213
+ self._indent = indent
214
+ DecoratedTree.__init__(self, tree)
215
+
216
+ def decorate(self, pos, widget, is_first=True):
217
+ indent = self._tree.depth(pos) * self._indent
218
+ cols = [(indent, urwid.SolidFill(' ')), widget]
219
+ # construct a Columns, defining all spacer as Box widgets
220
+ line = urwid.Columns(cols, box_columns=range(len(cols))[:-1])
221
+ return line
222
+
223
+
224
+ class CollapsibleIndentedTree(CollapseIconMixin, IndentedTree):
225
+ """
226
+ Indent collapsible tree nodes according to their depth in the tree and
227
+ display icons indicating collapse-status in the gaps.
228
+ """
229
+ def __init__(self, walker, icon_offset=1, indent=4, **kwargs):
230
+ """
231
+ :param walker: tree of widgets to be displayed
232
+ :type walker: Tree
233
+ :param indent: indentation width
234
+ :type indent: int
235
+ :param icon_offset: distance from icon to the eginning of the tree
236
+ node.
237
+ :type icon_offset: int
238
+ """
239
+ self._icon_offset = icon_offset
240
+ IndentedTree.__init__(self, walker, indent=indent)
241
+ CollapseIconMixin.__init__(self, **kwargs)
242
+
243
+ def decorate(self, pos, widget, is_first=True):
244
+ """
245
+ builds a list element for given position in the tree.
246
+ It consists of the original widget taken from the Tree and some
247
+ decoration columns depending on the existence of parent and sibling
248
+ positions. The result is a urwid.Columns widget.
249
+ """
250
+ void = urwid.SolidFill(' ')
251
+ line = None
252
+ cols = []
253
+ depth = self._tree.depth(pos)
254
+
255
+ # add spacer filling all but the last indent
256
+ if depth > 0:
257
+ cols.append((depth * self._indent, void)), # spacer
258
+
259
+ # construct last indent
260
+ # TODO
261
+ iwidth, icon = self._construct_collapse_icon(pos)
262
+ available_space = self._indent
263
+ firstindent_width = self._icon_offset + iwidth
264
+
265
+ # stop if indent is too small for this decoration
266
+ if firstindent_width > available_space:
267
+ raise NoSpaceError()
268
+
269
+ # add icon only for non-leafs
270
+ is_leaf = self._tree.is_leaf(pos)
271
+ if not is_leaf:
272
+ if icon is not None:
273
+ # space to the left
274
+ cols.append((available_space - firstindent_width,
275
+ urwid.SolidFill(' ')))
276
+ # icon
277
+ icon_pile = urwid.Pile([('pack', icon), void])
278
+ cols.append((iwidth, icon_pile))
279
+ # spacer until original widget
280
+ available_space = self._icon_offset
281
+ cols.append((available_space, urwid.SolidFill(' ')))
282
+ else: # otherwise just add another spacer
283
+ cols.append((self._indent, urwid.SolidFill(' ')))
284
+
285
+ cols.append(widget) # original widget ]
286
+ # construct a Columns, defining all spacer as Box widgets
287
+ line = urwid.Columns(cols, box_columns=range(len(cols))[:-1])
288
+
289
+ return line
290
+
291
+
292
+ class ArrowTree(IndentedTree):
293
+ """
294
+ Decorates the tree by indenting nodes according to their depth and using
295
+ the gaps to draw arrows indicate the tree structure.
296
+ """
297
+ def __init__(self, walker,
298
+ indent=3,
299
+ childbar_offset=0,
300
+ arrow_hbar_char=u'\u2500',
301
+ arrow_hbar_att=None,
302
+ arrow_vbar_char=u'\u2502',
303
+ arrow_vbar_att=None,
304
+ arrow_tip_char=u'\u27a4',
305
+ arrow_tip_att=None,
306
+ arrow_att=None,
307
+ arrow_connector_tchar=u'\u251c',
308
+ arrow_connector_lchar=u'\u2514',
309
+ arrow_connector_att=None, **kwargs):
310
+ """
311
+ :param walker: tree of widgets to be displayed
312
+ :type walker: Tree
313
+ :param indent: indentation width
314
+ :type indent: int
315
+ """
316
+ IndentedTree.__init__(self, walker, indent)
317
+ self._childbar_offset = childbar_offset
318
+ self._arrow_hbar_char = arrow_hbar_char
319
+ self._arrow_hbar_att = arrow_hbar_att
320
+ self._arrow_vbar_char = arrow_vbar_char
321
+ self._arrow_vbar_att = arrow_vbar_att
322
+ self._arrow_connector_lchar = arrow_connector_lchar
323
+ self._arrow_connector_tchar = arrow_connector_tchar
324
+ self._arrow_connector_att = arrow_connector_att
325
+ self._arrow_tip_char = arrow_tip_char
326
+ self._arrow_tip_att = arrow_tip_att
327
+ self._arrow_att = arrow_att
328
+
329
+ def _construct_spacer(self, pos, acc):
330
+ """
331
+ build a spacer that occupies the horizontally indented space between
332
+ pos's parent and the root node. It will return a list of tuples to be
333
+ fed into a Columns widget.
334
+ """
335
+ parent = self._tree.parent_position(pos)
336
+ if parent is not None:
337
+ grandparent = self._tree.parent_position(parent)
338
+ if self._indent > 0 and grandparent is not None:
339
+ parent_sib = self._tree.next_sibling_position(parent)
340
+ draw_vbar = parent_sib is not None and \
341
+ self._arrow_vbar_char is not None
342
+ space_width = self._indent - 1 * (draw_vbar) - self._childbar_offset
343
+ if space_width > 0:
344
+ void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
345
+ acc.insert(0, ((space_width, void)))
346
+ if draw_vbar:
347
+ barw = urwid.SolidFill(self._arrow_vbar_char)
348
+ bar = urwid.AttrMap(barw, self._arrow_vbar_att or
349
+ self._arrow_att)
350
+ acc.insert(0, ((1, bar)))
351
+ return self._construct_spacer(parent, acc)
352
+ else:
353
+ return acc
354
+
355
+ def _construct_connector(self, pos):
356
+ """
357
+ build widget to be used as "connector" bit between the vertical bar
358
+ between siblings and their respective horizontal bars leading to the
359
+ arrow tip
360
+ """
361
+ # connector symbol, either L or |- shaped.
362
+ connectorw = None
363
+ connector = None
364
+ if self._tree.next_sibling_position(pos) is not None: # |- shaped
365
+ if self._arrow_connector_tchar is not None:
366
+ connectorw = urwid.Text(self._arrow_connector_tchar)
367
+ else: # L shaped
368
+ if self._arrow_connector_lchar is not None:
369
+ connectorw = urwid.Text(self._arrow_connector_lchar)
370
+ if connectorw is not None:
371
+ att = self._arrow_connector_att or self._arrow_att
372
+ connector = urwid.AttrMap(connectorw, att)
373
+ return connector
374
+
375
+ def _construct_arrow_tip(self, pos):
376
+ """returns arrow tip as (width, widget)"""
377
+ arrow_tip = None
378
+ width = 0
379
+ if self._arrow_tip_char:
380
+ txt = urwid.Text(self._arrow_tip_char)
381
+ arrow_tip = urwid.AttrMap(
382
+ txt, self._arrow_tip_att or self._arrow_att)
383
+ width = len(self._arrow_tip_char)
384
+ return width, arrow_tip
385
+
386
+ def _construct_first_indent(self, pos):
387
+ """
388
+ build spacer to occupy the first indentation level from pos to the
389
+ left. This is separate as it adds arrowtip and sibling connector.
390
+ """
391
+ cols = []
392
+ void = urwid.AttrMap(urwid.SolidFill(' '), self._arrow_att)
393
+ available_width = self._indent
394
+
395
+ if self._tree.depth(pos) > 0:
396
+ connector = self._construct_connector(pos)
397
+ if connector is not None:
398
+ width = connector.pack()[0]
399
+ if width > available_width:
400
+ raise NoSpaceError()
401
+ available_width -= width
402
+ if self._tree.next_sibling_position(pos) is not None:
403
+ barw = urwid.SolidFill(self._arrow_vbar_char)
404
+ below = urwid.AttrMap(barw, self._arrow_vbar_att or
405
+ self._arrow_att)
406
+ else:
407
+ below = void
408
+ # pile up connector and bar
409
+ spacer = urwid.Pile([('pack', connector), below])
410
+ cols.append((width, spacer))
411
+
412
+ #arrow tip
413
+ awidth, at = self._construct_arrow_tip(pos)
414
+ if at is not None:
415
+ if awidth > available_width:
416
+ raise NoSpaceError()
417
+ available_width -= awidth
418
+ at_spacer = urwid.Pile([('pack', at), void])
419
+ cols.append((awidth, at_spacer))
420
+
421
+ # bar between connector and arrow tip
422
+ if available_width > 0:
423
+ barw = urwid.SolidFill(self._arrow_hbar_char)
424
+ bar = urwid.AttrMap(
425
+ barw, self._arrow_hbar_att or self._arrow_att)
426
+ hb_spacer = urwid.Pile([(1, bar), void])
427
+ cols.insert(1, (available_width, hb_spacer))
428
+ return cols
429
+
430
+ def decorate(self, pos, widget, is_first=True):
431
+ """
432
+ builds a list element for given position in the tree.
433
+ It consists of the original widget taken from the Tree and some
434
+ decoration columns depending on the existence of parent and sibling
435
+ positions. The result is a urwid.Columns widget.
436
+ """
437
+ line = None
438
+ if pos is not None:
439
+ original_widget = widget
440
+ cols = self._construct_spacer(pos, [])
441
+
442
+ # Construct arrow leading from parent here,
443
+ # if we have a parent and indentation is turned on
444
+ if self._indent > 0:
445
+ if is_first:
446
+ indent = self._construct_first_indent(pos)
447
+ if indent is not None:
448
+ cols = cols + indent
449
+ else:
450
+ parent = self._tree.parent_position(pos)
451
+ if self._indent > 0 and parent is not None:
452
+ parent_sib = self._tree.next_sibling_position(pos)
453
+ draw_vbar = parent_sib is not None
454
+ void = urwid.AttrMap(urwid.SolidFill(' '),
455
+ self._arrow_att)
456
+ if self._childbar_offset > 0:
457
+ cols.append((self._childbar_offset, void))
458
+ if draw_vbar:
459
+ barw = urwid.SolidFill(self._arrow_vbar_char)
460
+ bar = urwid.AttrMap(
461
+ barw, self._arrow_vbar_att or self._arrow_att)
462
+ rspace_width = self._indent - \
463
+ 1 - self._childbar_offset
464
+ cols.append((1, bar))
465
+ cols.append((rspace_width, void))
466
+ else:
467
+ cols.append((self._indent, void))
468
+
469
+ # add the original widget for this line
470
+ cols.append(original_widget)
471
+ # construct a Columns, defining all spacer as Box widgets
472
+ line = urwid.Columns(cols, box_columns=range(len(cols))[:-1])
473
+ return line
474
+
475
+
476
+ class CollapsibleArrowTree(CollapseIconMixin, ArrowTree):
477
+ """Arrow-decoration that allows collapsing subtrees"""
478
+ def __init__(self, treelistwalker, icon_offset=0, indent=5, **kwargs):
479
+ self._icon_offset = icon_offset
480
+ ArrowTree.__init__(self, treelistwalker, indent, **kwargs)
481
+ CollapseIconMixin.__init__(self, **kwargs)
482
+
483
+ def _construct_arrow_tip(self, pos):
484
+
485
+ cols = []
486
+ overall_width = self._icon_offset
487
+
488
+ if self._icon_offset > 0:
489
+ # how often we repeat the hbar_char until width icon_offset is
490
+ # reached
491
+ hbar_char_count = len(self._arrow_hbar_char) / self._icon_offset
492
+ barw = urwid.Text(self._arrow_hbar_char * hbar_char_count)
493
+ bar = urwid.AttrMap(barw, self._arrow_hbar_att or self._arrow_att)
494
+ cols.insert(1, (self._icon_offset, bar))
495
+
496
+ # add icon only for non-leafs
497
+ if self.collapsible(pos):
498
+ iwidth, icon = self._construct_collapse_icon(pos)
499
+ if icon is not None:
500
+ cols.insert(0, (iwidth, icon))
501
+ overall_width += iwidth
502
+
503
+ # get arrow tip
504
+ awidth, tip = ArrowTree._construct_arrow_tip(self, pos)
505
+ if tip is not None:
506
+ cols.append((awidth, tip))
507
+ overall_width += awidth
508
+
509
+ return overall_width, urwid.Columns(cols)
@@ -0,0 +1,141 @@
1
+ # This is a backport of functools.lru_cache, which is part of the stdlib =>v3.3.
2
+ # http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/
3
+
4
+ from collections import namedtuple
5
+ from functools import update_wrapper
6
+ from threading import Lock
7
+
8
+ _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"])
9
+
10
+ def lru_cache(maxsize=100, typed=False):
11
+ """Least-recently-used cache decorator.
12
+
13
+ If *maxsize* is set to None, the LRU features are disabled and the cache
14
+ can grow without bound.
15
+
16
+ If *typed* is True, arguments of different types will be cached separately.
17
+ For example, f(3.0) and f(3) will be treated as distinct calls with
18
+ distinct results.
19
+
20
+ Arguments to the cached function must be hashable.
21
+
22
+ View the cache statistics named tuple (hits, misses, maxsize, currsize) with
23
+ f.cache_info(). Clear the cache and statistics with f.cache_clear().
24
+ Access the underlying function with f.__wrapped__.
25
+
26
+ See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
27
+
28
+ """
29
+
30
+ # Users should only access the lru_cache through its public API:
31
+ # cache_info, cache_clear, and f.__wrapped__
32
+ # The internals of the lru_cache are encapsulated for thread safety and
33
+ # to allow the implementation to change (including a possible C version).
34
+
35
+ def decorating_function(user_function):
36
+
37
+ cache = dict()
38
+ stats = [0, 0] # make statistics updateable non-locally
39
+ HITS, MISSES = 0, 1 # names for the stats fields
40
+ kwd_mark = (object(),) # separate positional and keyword args
41
+ cache_get = cache.get # bound method to lookup key or return None
42
+ _len = len # localize the global len() function
43
+ lock = Lock() # because linkedlist updates aren't threadsafe
44
+ root = [] # root of the circular doubly linked list
45
+ nonlocal_root = [root] # make updateable non-locally
46
+ root[:] = [root, root, None, None] # initialize by pointing to self
47
+ PREV, NEXT, KEY, RESULT = 0, 1, 2, 3 # names for the link fields
48
+
49
+ def make_key(args, kwds, typed, tuple=tuple, sorted=sorted, type=type):
50
+ # helper function to build a cache key from positional and keyword args
51
+ key = args
52
+ if kwds:
53
+ sorted_items = tuple(sorted(kwds.items()))
54
+ key += kwd_mark + sorted_items
55
+ if typed:
56
+ key += tuple(type(v) for v in args)
57
+ if kwds:
58
+ key += tuple(type(v) for k, v in sorted_items)
59
+ return key
60
+
61
+ if maxsize == 0:
62
+
63
+ def wrapper(*args, **kwds):
64
+ # no caching, just do a statistics update after a successful call
65
+ result = user_function(*args, **kwds)
66
+ stats[MISSES] += 1
67
+ return result
68
+
69
+ elif maxsize is None:
70
+
71
+ def wrapper(*args, **kwds):
72
+ # simple caching without ordering or size limit
73
+ key = make_key(args, kwds, typed) if kwds or typed else args
74
+ result = cache_get(key, root) # root used here as a unique not-found sentinel
75
+ if result is not root:
76
+ stats[HITS] += 1
77
+ return result
78
+ result = user_function(*args, **kwds)
79
+ cache[key] = result
80
+ stats[MISSES] += 1
81
+ return result
82
+
83
+ else:
84
+
85
+ def wrapper(*args, **kwds):
86
+ # size limited caching that tracks accesses by recency
87
+ key = make_key(args, kwds, typed) if kwds or typed else args
88
+ with lock:
89
+ link = cache_get(key)
90
+ if link is not None:
91
+ # record recent use of the key by moving it to the front of the list
92
+ root, = nonlocal_root
93
+ link_prev, link_next, key, result = link
94
+ link_prev[NEXT] = link_next
95
+ link_next[PREV] = link_prev
96
+ last = root[PREV]
97
+ last[NEXT] = root[PREV] = link
98
+ link[PREV] = last
99
+ link[NEXT] = root
100
+ stats[HITS] += 1
101
+ return result
102
+ result = user_function(*args, **kwds)
103
+ with lock:
104
+ root = nonlocal_root[0]
105
+ if _len(cache) < maxsize:
106
+ # put result in a new link at the front of the list
107
+ last = root[PREV]
108
+ link = [last, root, key, result]
109
+ cache[key] = last[NEXT] = root[PREV] = link
110
+ else:
111
+ # use root to store the new key and result
112
+ root[KEY] = key
113
+ root[RESULT] = result
114
+ cache[key] = root
115
+ # empty the oldest link and make it the new root
116
+ root = nonlocal_root[0] = root[NEXT]
117
+ del cache[root[KEY]]
118
+ root[KEY] = None
119
+ root[RESULT] = None
120
+ stats[MISSES] += 1
121
+ return result
122
+
123
+ def cache_info():
124
+ """Report cache statistics"""
125
+ with lock:
126
+ return _CacheInfo(stats[HITS], stats[MISSES], maxsize, len(cache))
127
+
128
+ def cache_clear():
129
+ """Clear the cache and cache statistics"""
130
+ with lock:
131
+ cache.clear()
132
+ root = nonlocal_root[0]
133
+ root[:] = [root, root, None, None]
134
+ stats[:] = [0, 0]
135
+
136
+ wrapper.__wrapped__ = user_function
137
+ wrapper.cache_info = cache_info
138
+ wrapper.cache_clear = cache_clear
139
+ return update_wrapper(wrapper, user_function)
140
+
141
+ return decorating_function