-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.py
2609 lines (2262 loc) · 89.4 KB
/
memory.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## {{{ http://code.activestate.com/recipes/546530/ (r13)
#!/usr/bin/env python
# Copyright, license and disclaimer are at the end of this file.
# This is the latest, enhanced version of the asizeof.py recipes at
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/546530>
# <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/544288>
'''This module exposes 10 functions and 2 classes to obtain lengths
and sizes of Python objects (for Python 2.2 or later [1]).
The main changes in this version are new function calcsize(),
use gc.get_objects() to get all objects and improvements in
this documentation.
Public Functions [2]
Function asizeof calculates the combined (approximate) size
in bytes of one or several Python objects.
Function asizesof returns a tuple containing the (approximate)
size in bytes for each given Python object separately.
Function asized returns for each object an instance of class
Asized containing all the size information of the object and a
tuple with the referents.
Functions basicsize and itemsize return the basic respectively
item size of the given object.
Function flatsize returns the flat size of a Python object in
bytes defined as the basic size plus the item size times the
length of the given object.
Function leng returns the length of an object, like standard
len but extended for several types, e.g. the leng of a multi-
precision int (or long) is the number of digits [3]. The length
of most mutable sequence objects includes an estimate of the
over-allocation and therefore, the leng value may differ from
the standard len result.
Function refs returns (a generator for) the referents of the
given object, i.e. the objects referenced by the given object.
Function calcsize is equivalent to standard struct.calcsize
but handles format characters 'z' for signed C type Py_ssize_t
and 'Z' for unsigned C type size_t.
Certain classes are known to be sub-classes of or to behave as
dict objects. Function adict can be used to install other
class objects to be treated like dict.
Public Classes [2]
An instance of class Asized is returned for each object sized
with the asized function or method.
Class Asizer can be used to accumulate the results of several
asizeof or asizesof calls. After creating an Asizer instance,
use methods asizeof and asizesof to size additional objects.
Call methods exclude_refs and/or exclude_types to exclude
references to or instances or types of certain objects.
Use one of the print\_... methods to report the statistics.
Duplicate Objects
Any duplicate, given objects are sized only once and the size
is included in the combined total only once. But functions
asizesof and asized do return a size value respectively an
Asized instance for each given object, the same for duplicates.
Definitions [4]
The size of an object is defined as the sum of the flat size
of the object plus the sizes of any referents. Referents are
visited recursively up to a given limit. However, the size
of objects referenced multiple times is included only once.
The flat size of an object is defined as the basic size of the
object plus the item size times the number of allocated items.
The flat size does include the size for the items (references
to the referents), but not the referents themselves.
The flat size returned by function flatsize equals the result
of the asizeof function with options code=True, ignored=False,
limit=0 and option align set to the same value.
The accurate flat size for an object is obtained from function
sys.getsizeof() where available. Otherwise, the length and
size of sequence objects as dicts, lists, sets, etc. is based
on an estimate for the number of allocated items. As a result,
the reported length and size may substantially differ from the
actual length and size.
The basic and item sizes are obtained from the __basicsize__
respectively __itemsize__ attribute of the (type of the) object.
Where necessary (e.g. sequence objects), a zero __itemsize__
is replaced by the size of a corresponding C type.
The basic size (of GC managed objects) objects includes the
overhead for Python's garbage collector (GC) as well as the
space needed for refcounts (only in certain Python builds).
Optionally, sizes can be aligned to any power of 2 multiple.
Size of (byte)code
The (byte)code size of objects as classes, functions, methods,
modules, etc. can be included by setting option code.
Iterators are handled similar to sequences: iterated object(s)
are sized like referents if the recursion limit permits. Also,
function gc.get_referents() must return the referent object
of iterators.
Generators are sized as (byte)code only, but generated objects
are never sized.
Old- and New-style Classes
All old- and new-style class, instance and type objects, are
handled uniformly such that (a) instance and class objects can
be distinguished and (b) instances of different old-style
classes can be dealt with separately.
Class and type objects are represented as <class ....* def>
respectively as <type ... def> where an '*' indicates an old-
style class and the def suffix marks the definition object.
Instances of old-style classes are shown as new-style ones but
with an '*' at the end of the name, like <class module.name*>.
Ignored Objects
To avoid excessive sizes, several object types are ignored [4]
by default, e.g. built-in functions, built-in types and classes
[5], function globals and module referents. However, any
instances thereof are sized and module objects will be sized
when passed as given objects. Ignored object types are included
if option ignored is set accordingly.
In addition, many __...__ attributes of callable objects are
ignored, except crucial ones, e.g. class attributes __dict__,
__doc__, __name__ and __slots__. For more details, see the
type-specific _..._refs() and _len_...() functions below.
Option all can be used to size all Python objects and/or get
the referents from gc.get_referents() and override the type-
specific __..._refs() functions.
Notes
[1] Tested with Python 2.2.3, 2.3.7, 2.4.5, 2.5.1, 2.5.2, 2.6.2,
3.0.1 or 3.1a2 on CentOS 4.6, SuSE 9.3, MacOS X 10.4.11 Tiger
(Intel) and 10.3.9 Panther (PPC), Solaris 10 (Opteron) and
Windows XP all 32-bit Python and on RHEL 3u7 and Solaris 10
(Opteron) both 64-bit Python.
[2] The functions and classes in this module are not thread-safe.
[3] See Python source file .../Include/longinterp.h for the
C typedef of digit used in multi-precision int (or long)
objects. The size of digit in bytes can be obtained in
Python from the int (or long) __itemsize__ attribute.
Function leng (rather _len_int) below deterimines the
number of digits from the int (or long) value.
[4] These definitions and other assumptions are rather arbitrary
and may need corrections or adjustments.
[5] Types and classes are considered built-in if the module of
the type or class is listed in _builtin_modules below.
''' #PYCHOK expected
from __future__ import generators #PYCHOK for yield in Python 2.2
from inspect import isbuiltin, isclass, iscode, isframe, \
isfunction, ismethod, ismodule, stack
from math import log
from os import linesep
from struct import calcsize as _calcsize
import sys
import types as Types
import weakref as Weakref
__version__ = '5.12 (Apr 27, 2009)'
__all__ = ['adict', 'asized', 'asizeof', 'asizesof',
'Asized', 'Asizer', # classes
'basicsize', 'flatsize', 'itemsize', 'leng', 'refs',
'calcsize'] # handles 'z' and 'Z'
# any classes or types in modules listed in _builtin_modules are
# considered built-in and ignored by default, as built-in functions
if __name__ == '__main__':
_builtin_modules = (int.__module__, 'types', Exception.__module__) # , 'weakref'
else: # treat this very module as built-in
_builtin_modules = (int.__module__, 'types', Exception.__module__, __name__) # , 'weakref'
# sizes of some primitive C types
# XXX len(pack(T, 0)) == Struct(T).size == _calcsize(T)
# but type/class Struct only available since Python 2.5
_sizeof_Cbyte = _calcsize('c') # sizeof(unsigned char)
_sizeof_Clong = _calcsize('l') # sizeof(long)
_sizeof_Cvoidp = _calcsize('P') # sizeof(void*)
# sizeof(long) != sizeof(ssize_t) on LLP64
if _sizeof_Clong < _sizeof_Cvoidp:
_Zz = 'PP'
else:
_Zz = 'Ll'
def calcsize(fmt):
'''struct.calcsize() handling 'z' for signed Py_ssize_t and 'Z' for unsigned size_t.
'''
return _calcsize(fmt.replace('Z', _Zz[0]).replace('z', _Zz[1]))
# defaults for some basic sizes with 'z' for C Py_ssize_t
_sizeof_CPyCodeObject = calcsize('Pz10P5i0P') # sizeof(PyCodeObject)
_sizeof_CPyFrameObject = calcsize('Pzz13P63i0P') # sizeof(PyFrameObject)
_sizeof_CPyModuleObject = calcsize('PzP0P') # sizeof(PyModuleObject)
# defaults for some item sizes with 'z' for C Py_ssize_t
_sizeof_CPyDictEntry = calcsize('z2P') # sizeof(PyDictEntry)
_sizeof_Csetentry = calcsize('lP') # sizeof(setentry)
# XXX use sys.int_info.sizeof_digit in Python 3.1
try: # C typedef digit for multi-precision int (or long)
_sizeof_Cdigit = long.__itemsize__
except NameError: # no long in Python 3.0
_sizeof_Cdigit = int.__itemsize__
if _sizeof_Cdigit < 2:
raise AssertionError('sizeof(%s) bad: %d' % ('digit', _sizeof_Cdigit))
try: # sizeof(unicode_char)
u = unicode('\0')
except NameError: # no unicode() in Python 3.0
u = '\0'
u = u.encode('unicode-internal') # see .../Lib/test/test_sys.py
_sizeof_Cunicode = len(u)
del u
if (1 << (_sizeof_Cunicode << 3)) <= sys.maxunicode:
raise AssertionError('sizeof(%s) bad: %d' % ('unicode', _sizeof_Cunicode))
if hasattr(sys, 'maxsize'): # new in Python 2.6
Z = calcsize('Z') # check sizeof(size_t)
if (1 << (Z << 3)) <= sys.maxsize:
raise AssertionError('sizeof(%s) bad: %d' % ('size_t', Z))
del Z
try: # size of GC header, sizeof(PyGC_Head)
import _testcapi as t
_sizeof_CPyGC_Head = t.SIZEOF_PYGC_HEAD # new in Python 2.6
except (ImportError, AttributeError): # sizeof(PyGC_Head)
# alignment should be to sizeof(long double) but there
# is no way to obtain that value, assume twice double
t = calcsize('2d') - 1
_sizeof_CPyGC_Head = (calcsize('2Pz') + t) & ~t
del t
# size of refcounts (Python debug build only)
if hasattr(sys, 'gettotalrefcount'):
_sizeof_Crefcounts = calcsize('2z')
else:
_sizeof_Crefcounts = 0
# some flags from .../Include/object.h
_Py_TPFLAGS_HEAPTYPE = 1 << 9 # Py_TPFLAGS_HEAPTYPE
_Py_TPFLAGS_HAVE_GC = 1 << 14 # Py_TPFLAGS_HAVE_GC
_Type_type = type(type) # == type and new-style class type
# compatibility functions for more uniform
# behavior across Python version 2.2 thu 3.0
def _items(obj): # dict only
'''Return iter-/generator, preferably.
'''
return getattr(obj, 'iteritems', obj.items)()
def _keys(obj): # dict only
'''Return iter-/generator, preferably.
'''
return getattr(obj, 'iterkeys', obj.keys)()
def _values(obj): # dict only
'''Use iter-/generator, preferably.
'''
return getattr(obj, 'itervalues', obj.values)()
try: # callable() builtin
_callable = callable
except NameError: # callable() removed in Python 3.0
def _callable(obj):
'''Substitute for callable().'''
return hasattr(obj, '__call__')
try: # get 'all' current objects
from gc import get_objects as _getobjects
except ImportError:
def _getobjects():
# modules first, globals and stack
# (may contain duplicate objects)
return tuple(_values(sys.modules)) + (
globals(), stack(sys.getrecursionlimit()))
try: # get 'all' referents of objects
# note that gc.get_referents()
# returns () for dict...-iterators
from gc import get_referents as _getreferents
except ImportError: # no get_referents() in Python 2.2
def _getreferents(unused):
return () # sorry, no refs
# sys.getsizeof() new in Python 2.6
_getsizeof = getattr(sys, 'getsizeof', None)
try: # str intern()
_intern = intern
except NameError: # no intern() in Python 3.0
def _intern(val):
return val
def _kwds(**kwds): # no dict(key=value, ...) in Python 2.2
'''Return name=value pairs as keywords dict.
'''
return kwds
try: # sorted() builtin
_sorted = sorted
except NameError: # no sorted() in Python 2.2
def _sorted(vals, reverse=False):
'''Partial substitute for missing sorted().'''
vals.sort() # inplace OK
if reverse:
vals.reverse()
return vals
try: # sum() builtin
_sum = sum
except NameError: # no sum() in Python 2.2
def _sum(vals):
'''Partial substitute for missing sum().'''
s = 0
for v in vals:
s += v
return s
# private functions
def _basicsize(t, base=0, heap=False, obj=None):
'''Get non-zero basicsize of type,
including the header sizes.
'''
s = max(getattr(t, '__basicsize__', 0), base)
# include gc header size
if t != _Type_type:
h = getattr(t, '__flags__', 0) & _Py_TPFLAGS_HAVE_GC
elif heap: # type, allocated on heap
h = True
else: # None has no __flags__ attr
h = getattr(obj, '__flags__', 0) & _Py_TPFLAGS_HEAPTYPE
if h:
s += _sizeof_CPyGC_Head
# include reference counters
return s + _sizeof_Crefcounts
def _derive_typedef(typ):
'''Return single, existing super type typedef or None.
'''
v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)]
if len(v) == 1:
return v[0]
return None
def _dir2(obj, pref='', excl=(), slots=None, itor=''):
'''Return an attribute name, object 2-tuple for certain
attributes or for the '__slots__' attributes of the
given object, but not both. Any iterator referent
objects are returned with the given name if the
latter is non-empty.
'''
if slots: # __slots__ attrs
if hasattr(obj, slots):
# collect all inherited __slots__ attrs
# from list, tuple, or dict __slots__,
# while removing any duplicate attrs
s = {}
for c in type(obj).mro():
for a in getattr(c, slots, ()):
if hasattr(obj, a):
s.setdefault(a, getattr(obj, a))
# assume __slots__ tuple/list
# is holding the attr values
yield slots, _Slots(s) # _keys(s)
for t in _items(s):
yield t # attr name, value
elif itor: # iterator referents
for o in obj: # iter(obj)
yield itor, o
else: # regular attrs
for a in dir(obj):
if a.startswith(pref) and a not in excl and hasattr(obj, a):
yield a, getattr(obj, a)
def _infer_dict(obj):
'''Return True for likely dict object.
'''
for ats in (('__len__', 'get', 'has_key', 'items', 'keys', 'values'),
('__len__', 'get', 'has_key', 'iteritems', 'iterkeys', 'itervalues')):
for a in ats: # no all(<generator_expression>) in Python 2.2
if not _callable(getattr(obj, a, None)):
break
else: # all True
return True
return False
def _isdictclass(obj):
'''Return True for known dict objects.
'''
c = getattr(obj, '__class__', None)
return c and c.__name__ in _dict_classes.get(c.__module__, ())
def _issubclass(sub, sup):
'''Safe issubclass().
'''
if sup is not object:
try:
return issubclass(sub, sup)
except TypeError:
pass
return False
def _itemsize(t, item=0):
'''Get non-zero itemsize of type.
'''
# replace zero value with default
return getattr(t, '__itemsize__', 0) or item
def _kwdstr(**kwds):
'''Keyword arguments as a string.
'''
return ', '.join(_sorted(['%s=%r' % kv for kv in _items(kwds)])) # [] for Python 2.2
def _lengstr(obj):
'''Object length as a string.
'''
n = leng(obj)
if n is None: # no len
r = ''
elif n > _len(obj): # extended
r = ' leng %d!' % n
else:
r = ' leng %d' % n
return r
def _nameof(obj, dflt=''):
'''Return the name of an object.
'''
return getattr(obj, '__name__', dflt)
def _objs(objs, all=None, **unused):
'''Return the given or 'all' objects.
'''
if all in (False, None):
t = objs or ()
elif all is True: # 'all' objects
t = objs or _getobjects()
else:
raise ValueError('invalid option: %s=%r' % ('all', all))
return t
def _p100(part, total, prec=1):
'''Return percentage as string.
'''
r = float(total)
if r:
r = part * 100.0 / r
return '%.*f%%' % (prec, r)
return 'n/a'
def _plural(num):
'''Return 's' if plural.
'''
if num == 1:
s = ''
else:
s = 's'
return s
def _power2(n):
'''Find the next power of 2.
'''
p2 = 16
while n > p2:
p2 += p2
return p2
def _prepr(obj, clip=0):
'''Prettify and clip long repr() string.
'''
return _repr(obj, clip=clip).strip('<>').replace("'", '') # remove <''>
def _printf(fmt, *args, **print3opts):
'''Formatted print.
'''
if print3opts: # like Python 3.0
f = print3opts.get('file', None) or sys.stdout
if args:
f.write(fmt % args)
else:
f.write(fmt)
f.write(print3opts.get('end', linesep))
elif args:
print(fmt % args)
else:
print(fmt)
def _refs(obj, named, *ats, **kwds):
'''Return specific attribute objects of an object.
'''
if named:
for a in ats: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _NamedRef(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _NamedRef(a, o)
else:
for a in ats: # cf. inspect.getmembers()
if hasattr(obj, a):
yield getattr(obj, a)
if kwds: # kwds are _dir2() args
for _, o in _dir2(obj, **kwds):
yield o
def _repr(obj, clip=80):
'''Clip long repr() string.
'''
try: # safe repr()
r = repr(obj)
except TypeError:
r = 'N/A'
if 0 < clip < len(r):
h = (clip // 2) - 2
if h > 0:
r = r[:h] + '....' + r[-h:]
return r
def _SI(size, K=1024, i='i'):
'''Return size as SI string.
'''
if 1 < K < size:
f = float(size)
for si in iter('KMGPTE'):
f /= K
if f < K:
return ' or %.1f %s%sB' % (f, si, i)
return ''
def _SI2(size, **kwds):
'''Return size as regular plus SI string.
'''
return str(size) + _SI(size, **kwds)
# type-specific referent functions
def _class_refs(obj, named):
'''Return specific referents of a class object.
'''
return _refs(obj, named, '__class__', '__dict__', '__doc__', '__mro__',
'__name__', '__slots__', '__weakref__')
def _co_refs(obj, named):
'''Return specific referents of a code object.
'''
return _refs(obj, named, pref='co_')
def _dict_refs(obj, named):
'''Return key and value objects of a dict/proxy.
'''
if named:
for k, v in _items(obj):
s = str(k)
yield _NamedRef(s, k, 1) # key
yield _NamedRef(s, v, 2) # value
else:
for k, v in _items(obj):
yield k
yield v
def _enum_refs(obj, named):
'''Return specific referents of an enumerate object.
'''
return _refs(obj, named, '__doc__')
def _exc_refs(obj, named):
'''Return specific referents of an Exception object.
'''
# .message raises DeprecationWarning in Python 2.6
return _refs(obj, named, 'args', 'filename', 'lineno', 'msg', 'text') # , 'message', 'mixed'
def _file_refs(obj, named):
'''Return specific referents of a file object.
'''
return _refs(obj, named, 'mode', 'name')
def _frame_refs(obj, named):
'''Return specific referents of a frame object.
'''
return _refs(obj, named, pref='f_')
def _func_refs(obj, named):
'''Return specific referents of a function or lambda object.
'''
return _refs(obj, named, '__doc__', '__name__', '__code__',
pref='func_', excl=('func_globals',))
def _gen_refs(obj, named):
'''Return the referent(s) of a generator object.
'''
# only some gi_frame attrs
f = getattr(obj, 'gi_frame', None)
return _refs(f, named, 'f_locals', 'f_code')
def _im_refs(obj, named):
'''Return specific referents of a method object.
'''
return _refs(obj, named, '__doc__', '__name__', '__code__',
pref='im_')
def _inst_refs(obj, named):
'''Return specific referents of a class instance.
'''
return _refs(obj, named, '__dict__', '__class__',
slots='__slots__')
def _iter_refs(obj, named):
'''Return the referent(s) of an iterator object.
'''
r = _getreferents(obj) # special case
return _refs(r, named, itor=_nameof(obj) or 'iteref')
def _module_refs(obj, named):
'''Return specific referents of a module object.
'''
# ignore this very module
if obj.__name__ == __name__:
return ()
# module is essentially a dict
return _dict_refs(obj.__dict__, named)
def _prop_refs(obj, named):
'''Return specific referents of a property object.
'''
return _refs(obj, named, '__doc__', pref='f')
def _seq_refs(obj, unused): # named unused for PyChecker
'''Return specific referents of a frozen/set, list, tuple and xrange object.
'''
return obj # XXX for r in obj: yield r
def _stat_refs(obj, named):
'''Return referents of a os.stat object.
'''
return _refs(obj, named, pref='st_')
def _statvfs_refs(obj, named):
'''Return referents of a os.statvfs object.
'''
return _refs(obj, named, pref='f_')
def _tb_refs(obj, named):
'''Return specific referents of a traceback object.
'''
return _refs(obj, named, pref='tb_')
def _type_refs(obj, named):
'''Return specific referents of a type object.
'''
return _refs(obj, named, '__dict__', '__doc__', '__mro__',
'__name__', '__slots__', '__weakref__')
def _weak_refs(obj, unused): # named unused for PyChecker
'''Return weakly referent object.
'''
try: # ignore 'key' of KeyedRef
return (obj(),)
except: # XXX ReferenceError
return () #PYCHOK OK
_all_refs = (None, _class_refs, _co_refs, _dict_refs, _enum_refs,
_exc_refs, _file_refs, _frame_refs, _func_refs,
_gen_refs, _im_refs, _inst_refs, _iter_refs,
_module_refs, _prop_refs, _seq_refs, _stat_refs,
_statvfs_refs, _tb_refs, _type_refs, _weak_refs)
# type-specific length functions
def _len(obj):
'''Safe len().
'''
try:
return len(obj)
except TypeError: # no len()
return 0
def _len_array(obj):
'''Array length in bytes.
'''
return len(obj) * obj.itemsize
def _len_bytearray(obj):
'''Bytearray size.
'''
return obj.__alloc__()
def _len_code(obj): # see .../Lib/test/test_sys.py
'''Length of code object (stack and variables only).
'''
return obj.co_stacksize + obj.co_nlocals \
+ _len(obj.co_freevars) \
+ _len(obj.co_cellvars) - 1
def _len_dict(obj):
'''Dict length in items (estimate).
'''
n = len(obj) # active items
if n < 6: # ma_smalltable ...
n = 0 # ... in basicsize
else: # at least one unused
n = _power2(n + 1)
return n
def _len_frame(obj):
'''Length of a frame object.
'''
c = getattr(obj, 'f_code', None)
if c:
n = _len_code(c)
else:
n = 0
return n
_digit2p2 = 1 << (_sizeof_Cdigit << 3)
_digitmax = _digit2p2 - 1 # == (2 * PyLong_MASK + 1)
_digitlog = 1.0 / log(_digit2p2)
def _len_int(obj):
'''Length of multi-precision int (aka long) in digits.
'''
if obj:
n, i = 1, abs(obj)
if i > _digitmax:
# no log(x[, base]) in Python 2.2
n += int(log(i) * _digitlog)
else: # zero
n = 0
return n
def _len_iter(obj):
'''Length (hint) of an iterator.
'''
n = getattr(obj, '__length_hint__', None)
if n:
n = n()
else: # try len()
n = _len(obj)
return n
def _len_list(obj):
'''Length of list (estimate).
'''
n = len(obj)
# estimate over-allocation
if n > 8:
n += 6 + (n >> 3)
elif n:
n += 4
return n
def _len_module(obj):
'''Module length.
'''
return _len(obj.__dict__) # _len(dir(obj))
def _len_set(obj):
'''Length of frozen/set (estimate).
'''
n = len(obj)
if n > 8: # assume half filled
n = _power2(n + n - 2)
elif n: # at least 8
n = 8
return n
def _len_slice(obj):
'''Slice length.
'''
try:
return ((obj.stop - obj.start + 1) // obj.step)
except (AttributeError, TypeError):
return 0
def _len_slots(obj):
'''Slots length.
'''
return len(obj) - 1
def _len_struct(obj):
'''Struct length in bytes.
'''
try:
return obj.size
except AttributeError:
return 0
def _len_unicode(obj):
'''Unicode size.
'''
return len(obj) + 1
_all_lengs = (None, _len, _len_array, _len_bytearray,
_len_code, _len_dict, _len_frame,
_len_int, _len_iter, _len_list,
_len_module, _len_set, _len_slice,
_len_slots, _len_struct, _len_unicode)
# more private functions and classes
_old_style = '*' # marker
_new_style = '' # no marker
class _Claskey(object):
'''Wrapper for class objects.
'''
__slots__ = ('_obj', '_sty')
def __init__(self, obj, style):
self._obj = obj # XXX Weakref.ref(obj)
self._sty = style
def __str__(self):
r = str(self._obj)
if r.endswith('>'):
r = '%s%s def>' % (r[:-1], self._sty)
elif self._sty is _old_style and not r.startswith('class '):
r = 'class %s%s def' % (r, self._sty)
else:
r = '%s%s def' % (r, self._sty)
return r
__repr__ = __str__
# For most objects, the object type is used as the key in the
# _typedefs dict further below, except class and type objects
# and old-style instances. Those are wrapped with separate
# _Claskey or _Instkey instances to be able (1) to distinguish
# instances of different old-style classes by class, (2) to
# distinguish class (and type) instances from class (and type)
# definitions for new-style classes and (3) provide similar
# results for repr() and str() of new- and old-style classes
# and instances.
_claskeys = {} # [id(obj)] = _Claskey()
def _claskey(obj, style):
'''Wrap an old- or new-style class object.
'''
i = id(obj)
k = _claskeys.get(i, None)
if not k:
_claskeys[i] = k = _Claskey(obj, style)
return k
try: # no Class- and InstanceType in Python 3.0
_Types_ClassType = Types.ClassType
_Types_InstanceType = Types.InstanceType
class _Instkey(object):
'''Wrapper for old-style class (instances).
'''
__slots__ = ('_obj',)
def __init__(self, obj):
self._obj = obj # XXX Weakref.ref(obj)
def __str__(self):
return '<class %s.%s%s>' % (self._obj.__module__, self._obj.__name__, _old_style)
__repr__ = __str__
_instkeys = {} # [id(obj)] = _Instkey()
def _instkey(obj):
'''Wrap an old-style class (instance).
'''
i = id(obj)
k = _instkeys.get(i, None)
if not k:
_instkeys[i] = k = _Instkey(obj)
return k
def _keytuple(obj):
'''Return class and instance keys for a class.
'''
t = type(obj)
if t is _Types_InstanceType:
t = obj.__class__
return _claskey(t, _old_style), _instkey(t)
elif t is _Types_ClassType:
return _claskey(obj, _old_style), _instkey(obj)
elif t is _Type_type:
return _claskey(obj, _new_style), obj
return None, None # not a class
def _objkey(obj):
'''Return the key for any object.
'''
k = type(obj)
if k is _Types_InstanceType:
k = _instkey(obj.__class__)
elif k is _Types_ClassType:
k = _claskey(obj, _old_style)
elif k is _Type_type:
k = _claskey(obj, _new_style)
return k
except AttributeError: # Python 3.0
def _keytuple(obj): #PYCHOK expected
'''Return class and instance keys for a class.
'''
if type(obj) is _Type_type: # isclass(obj):
return _claskey(obj, _new_style), obj
return None, None # not a class
def _objkey(obj): #PYCHOK expected
'''Return the key for any object.
'''
k = type(obj)
if k is _Type_type: # isclass(obj):
k = _claskey(obj, _new_style)
return k
class _NamedRef(object):
'''Store referred object along
with the name of the referent.
'''
__slots__ = ('name', 'ref', 'typ')
def __init__(self, name, ref, typ=0):
self.name = name
self.ref = ref
self.typ = typ # see Asized.format
class _Slots(tuple):
'''Wrapper class for __slots__ attribute at
class instances to account for the size
of the __slots__ tuple/list containing
references to the attribute values.
'''
pass
# kinds of _Typedefs
_i = _intern
_all_kinds = (_kind_static, _kind_dynamic, _kind_derived, _kind_ignored, _kind_inferred) = (
_i('static'), _i('dynamic'), _i('derived'), _i('ignored'), _i('inferred'))
del _i
class _Typedef(object):
'''Type definition class.
'''
__slots__ = {
'base': 0, # basic size in bytes
'item': 0, # item size in bytes
'leng': None, # or _len_...() function
'refs': None, # or _..._refs() function
'both': None, # both data and code if True, code only if False
'kind': None, # _kind_... value
'type': None} # original type
def __init__(self, **kwds):
self.reset(**kwds)
def __lt__(self, unused): # for Python 3.0
return True
def __repr__(self):
return repr(self.args())
def __str__(self):
t = [str(self.base), str(self.item)]
for f in (self.leng, self.refs):
if f:
t.append(f.__name__)