10
10
"""
11
11
12
12
from __future__ import print_function
13
- import weakref , os , six
14
- from collections import defaultdict
13
+ import weakref
15
14
from time import time
16
15
from operator import itemgetter
16
+ from collections import defaultdict
17
+ import six
17
18
18
- NoneType = type (None )
19
19
20
+ NoneType = type (None )
20
21
live_refs = defaultdict (weakref .WeakKeyDictionary )
21
22
23
+
22
24
class object_ref (object ):
23
25
"""Inherit from this class (instead of object) to a keep a record of live
24
26
instances"""
@@ -30,29 +32,40 @@ def __new__(cls, *args, **kwargs):
30
32
live_refs [cls ][obj ] = time ()
31
33
return obj
32
34
35
+
33
36
def format_live_refs (ignore = NoneType ):
34
- s = "Live References" + os .linesep + os .linesep
37
+ """Return a tabular representation of tracked objects"""
38
+ s = "Live References\n \n "
35
39
now = time ()
36
- for cls , wdict in six .iteritems (live_refs ):
40
+ for cls , wdict in sorted (six .iteritems (live_refs ),
41
+ key = lambda x : x [0 ].__name__ ):
37
42
if not wdict :
38
43
continue
39
44
if issubclass (cls , ignore ):
40
45
continue
41
- oldest = min (wdict .itervalues ())
42
- s += "%-30s %6d oldest: %ds ago" % (cls .__name__ , len (wdict ), \
43
- now - oldest ) + os .linesep
46
+ oldest = min (six .itervalues (wdict ))
47
+ s += "%-30s %6d oldest: %ds ago\n " % (
48
+ cls .__name__ , len (wdict ), now - oldest
49
+ )
44
50
return s
45
51
52
+
46
53
def print_live_refs (* a , ** kw ):
54
+ """Print tracked objects"""
47
55
print (format_live_refs (* a , ** kw ))
48
56
57
+
49
58
def get_oldest (class_name ):
59
+ """Get the oldest object for a specific class name"""
50
60
for cls , wdict in six .iteritems (live_refs ):
51
61
if cls .__name__ == class_name :
52
- if wdict :
53
- return min (six .iteritems (wdict ), key = itemgetter (1 ))[0 ]
62
+ if not wdict :
63
+ break
64
+ return min (six .iteritems (wdict ), key = itemgetter (1 ))[0 ]
65
+
54
66
55
67
def iter_all (class_name ):
68
+ """Iterate over all objects of the same class by its class name"""
56
69
for cls , wdict in six .iteritems (live_refs ):
57
70
if cls .__name__ == class_name :
58
71
return six .iterkeys (wdict )
0 commit comments