1
+ from lru import LRU
2
+ l = LRU (5 ) # Create an LRU container that can hold 5 items
3
+
4
+ print (l .peek_first_item (), l .peek_last_item ()) #return the MRU key and LRU key
5
+ # Would print None None
6
+
7
+ for i in range (5 ):
8
+ l [i ] = str (i )
9
+ print (l .items ()) # Prints items in MRU order
10
+ # Would print [(4, '4'), (3, '3'), (2, '2'), (1, '1'), (0, '0')]
11
+
12
+ print (l .peek_first_item (), l .peek_last_item ()) #return the MRU key and LRU key
13
+ # Would print (4, '4') (0, '0')
14
+
15
+ l [5 ] = '5' # Inserting one more item should evict the old item
16
+ print (l .items ())
17
+ # Would print [(5, '5'), (4, '4'), (3, '3'), (2, '2'), (1, '1')]
18
+
19
+ l [3 ] # Accessing an item would make it MRU
20
+ print (l .items ())
21
+ # Would print [(3, '3'), (5, '5'), (4, '4'), (2, '2'), (1, '1')]
22
+ # Now 3 is in front
23
+
24
+ l .keys () # Can get keys alone in MRU order
25
+ # Would print [3, 5, 4, 2, 1]
26
+
27
+ del l [4 ] # Delete an item
28
+ print (l .items ())
29
+ # Would print [(3, '3'), (5, '5'), (2, '2'), (1, '1')]
30
+
31
+ print (l .get_size ())
32
+ # Would print 5
33
+
34
+ l .set_size (3 )
35
+ print (l .items ())
36
+ # Would print [(3, '3'), (5, '5'), (2, '2')]
37
+ print (l .get_size ())
38
+ # Would print 3
39
+ print (l .has_key (5 ))
40
+ # Would print True
41
+ print (2 in l )
42
+ # Would print True
43
+
44
+ l .get_stats ()
45
+ # Would print (1, 0)
46
+
47
+
48
+ l .update (5 = '0' ) # Update an item
49
+ print l .items ()
50
+ # Would print [(5, '0'), (3, '3'), (2, '2')]
51
+
52
+ l .clear ()
53
+ print l .items ()
54
+ # Would print []
55
+
56
+ def evicted (key , value ):
57
+ print "removing: %s, %s" % (key , value )
58
+
59
+ l = LRU (1 , callback = evicted )
60
+
61
+ l [1 ] = '1'
62
+ l [2 ] = '2'
63
+ # callback would print removing: 1, 1
64
+
65
+ l [2 ] = '3'
66
+ # doesn't call the evicted callback
67
+
68
+ print l .items ()
69
+ # would print [(2, '3')]
70
+
71
+ del l [2 ]
72
+ # doesn't call the evicted callback
73
+
74
+ print l .items ()
75
+ # would print []
0 commit comments