/
asizeof.py
executable file
·2960 lines (2408 loc) · 92.8 KB
/
asizeof.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
#!/usr/bin/env python
# Copyright, license and disclaimer are at the very 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>
# Note, objects like ``namedtuples``, ``closure``, and NumPy data
# ``arange``, ``array``, ``matrix``, etc. are only handled by recent
# versions of this module. Sizing of ``__slots__`` has been incorrect
# in versions before this one. Also, property ``Asizer.duplicate`` gave
# incorrect values before this release. Several other properties
# have been added to the ``Asizer`` class and the ``print_summary``
# method has been updated.
'''
This module exposes 9 functions and 2 classes to obtain lengths and
sizes of Python objects (for Python 2.6 or later).
Earlier versions of this module supported Python versions down to
Python 2.2. If you are using Python 2.5 or older, please consider
downgrading Pympler to version 0.3.x.
**Public Functions** [#unsafe]_
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 [#refs]_.
Functions **basicsize** and **itemsize** return the *basic-*
respectively *itemsize* of the given object, both in bytes. For
objects as ``array.array``, ``numpy.array``, ``numpy.matrix``,
etc. where the item size varies depending on the instance-specific
data type, function **itemsize** returns that item size.
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
function ``len`` but extended for several types. E.g. the **leng**
of a multi-precision int (or long) is the number of ``digits``
[#digit]_. 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. For objects like
``array.array``, ``numpy.array``, ``numpy.matrix``, etc. function
**leng** returns the proper number of items.
Function **refs** returns (a generator for) the referents [#refs]_
of the given object.
Certain classes are known to be sub-classes of or to behave as
``dict`` objects. Function **adict** can be used to register
other class objects to be treated like ``dict``.
**Public Classes** [#unsafe]_
Class **Asizer** may be used to accumulate the results of several
**asizeof** or **asizesof** calls. After creating an **Asizer**
instance, use methods **asizeof** and **asizesof** as needed to
size any number of additional objects.
Call methods **exclude_refs** and/or **exclude_types** to exclude
references to respectively instances or types of certain objects.
Use one of the **print\\_...** methods to report the statistics.
An instance of class **Asized** is returned for each object sized
by the **asized** function or method.
**Duplicate Objects**
Any duplicate, given objects are sized only once and the size
is included in the accumulated total only once. But functions
**asizesof** and **asized** will return a size value respectively
an **Asized** instance for each given object, including duplicates.
**Definitions** [#arb]_
The *length* of an objects like ``dict``, ``list``, ``set``,
``str``, ``tuple``, etc. is defined as the number of items held
in or allocated by the object. Held items are *references* to
other objects, called the *referents*.
The *size* of an object is defined as the sum of the *flat size*
of the object plus the sizes of any referents [#refs]_. Referents
are visited recursively up to the specified detail level. However,
the size of objects referenced multiple times is included only once
in the total *size*.
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*,
*references* to referents. The *flat size* does include the size
for the *references* to the referents, but not the size of the
referents themselves.
The *flat size* returned by function *flatsize* equals the result
of function *asizeof* 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 differ substantially
from the actual *length* and *size*.
The *basic* and *item size* are obtained from the ``__basicsize__``
respectively ``__itemsize__`` attributes 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 overhead for Python's garbage collector (GC) is included in
the *basic size* of (GC managed) objects as well as the space
needed for ``refcounts`` (used only in certain Python builds).
Optionally, size values can be aligned to any power-of-2 multiple.
**Size of (byte)code**
The *(byte)code size* of objects like classes, functions, methods,
modules, etc. can be included by setting option *code=True*.
Iterators are handled like sequences: iterated object(s) are sized
like *referents* [#refs]_, but only up to the specified level or
recursion *limit* (and only if function ``gc.get_referents()``
returns the referent object of iterators).
Generators are sized as *(byte)code* only, but the 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 objects are distinguished
from class objects and (b) instances of different old-style classes
can be dealt with separately.
Class and type objects are represented as ``<class ....* def>``
respectively ``<type ... def>`` where the ``*`` indicates an old-style
class and the ``... def`` suffix marks the *definition object*.
Instances of classes are shown as ``<class module.name*>`` without
the ``... def`` suffix. The ``*`` after the name indicates an
instance of an old-style class.
**Ignored Objects**
To avoid excessive sizes, several object types are ignored [#arb]_
by default, e.g. built-in functions, built-in types and classes
[#bi]_, function globals and module referents. However, any
instances thereof and module objects will be sized when passed as
given objects. Ignored object types are included unless option
*ignored* is set accordingly.
In addition, many ``__...__`` attributes of callable objects are
ignored [#arb]_, except crucial ones, e.g. class attributes ``__dict__``,
``__doc__``, ``__name__`` and ``__slots__``. For more details, see
the type-specific ``_..._refs()`` and ``_len_...()`` functions below.
.. rubric:: Footnotes
.. [#unsafe] The functions and classes in this module are not thread-safe.
.. [#refs] The *referents* of an object are the objects referenced *by*
that object. For example, the *referents* of a ``list`` are the
objects held in the ``list``, the *referents* of a ``dict`` are
the key and value objects in the ``dict``, etc.
.. [#arb] These definitions and other assumptions are rather arbitrary
and may need corrections or adjustments.
.. [#digit] See Python source file ``.../Include/longinterp.h`` for the
C ``typedef`` of ``digit`` used in multi-precision int (or long)
objects. The C ``sizeof(digit)`` in bytes can be obtained in
Python from the int (or long) ``__itemsize__`` attribute.
Function **leng** determines the number of ``digits`` of an int
(or long) object.
.. [#bi] ``Type``s and ``class``es are considered built-in if the
``__module__`` of the type or class is listed in the private
``_builtin_modules``.
''' # PYCHOK escape
import sys
if sys.version_info < (2, 6, 0):
raise NotImplementedError('%s requires Python 2.6 or newer' % ('asizeof',))
# all imports listed explicitly to help PyChecker
from inspect import (isbuiltin, isclass, iscode, isframe, isfunction,
ismethod, ismodule, stack)
from math import log
from os import curdir, linesep
from struct import calcsize # type/class Struct only in Python 2.5+
import types as Types
import warnings
import weakref as Weakref
__all__ = ['adict', 'asized', 'asizeof', 'asizesof',
'Asized', 'Asizer', # classes
'basicsize', 'flatsize', 'itemsize', 'leng', 'refs']
__version__ = '20.06.04'
# Any classes or types in modules listed in _builtin_modules are
# considered built-in and ignored by default, as built-in functions
_builtin_modules = (int.__module__, 'types', Exception.__module__) # 'weakref'
if __name__ != '__main__': # treat this very module as built-in
_builtin_modules += (__name__,)
# Sizes of some primitive C types
# XXX len(pack(T, 0)) == Struct(T).size == calcsize(T)
_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: # pragma: no coverage
_z_P_L = 'P'
else:
_z_P_L = 'L'
def _calcsize(fmt):
'''Like struct.calcsize() but handling 'z' for Py_ssize_t.
'''
return calcsize(fmt.replace('z', _z_P_L))
# 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)
try: # C typedef digit for multi-precision int (or long)
_sizeof_Cdigit = long.__itemsize__
except NameError: # no long in Python 3+
_sizeof_Cdigit = int.__itemsize__
if _sizeof_Cdigit < 2: # pragma: no coverage
raise AssertionError('sizeof(%s) bad: %d' % ('digit', _sizeof_Cdigit))
try:
_builtins2 = range, xrange
except NameError: # Python 3+
_builtins2 = range,
# Get character size for internal unicode representation in Python < 3.3
try: # sizeof(unicode_char)
u = unicode('\0')
except NameError: # no unicode() in Python 3+
u = '\0'
u = u.encode('utf-8')
_sizeof_Cunicode = len(u)
del u
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'): # pragma: no coverage
_sizeof_Crefcounts = _calcsize('2z')
else:
_sizeof_Crefcounts = 0
try:
from abc import ABCMeta
except ImportError:
class ABCMeta(type):
pass
# 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+
def _items(obj): # dict only
'''Return iter-/generator, preferably.
'''
o = getattr(obj, 'iteritems', obj.items)
if _callable(o):
return o()
else:
return o or ()
def _keys(obj): # dict only
'''Return iter-/generator, preferably.
'''
o = getattr(obj, 'iterkeys', obj.keys)
if _callable(o):
return o()
else:
return o or ()
def _values(obj): # dict only
'''Return iter-/generator, preferably.
'''
o = getattr(obj, 'itervalues', obj.values)
if _callable(o):
return o()
else:
return o or ()
try: # callable() builtin
_callable = callable
except NameError: # callable() removed in Python 3+
def _callable(obj):
'''Substitute for callable().'''
return hasattr(obj, '__call__')
# 'cell' is holding data used in closures
c = (lambda unused: (lambda: unused))(None)
try:
_cell_type = type(c.__closure__[0])
except AttributeError: # Python 2.5
_cell_type = type(c.func_closure[0])
del c
try:
from gc import get_objects as _getobjects # containers only?
except ImportError:
def _getobjects():
# modules first, globals and stack
# objects (may contain duplicates)
return tuple(_values(sys.modules)) + (
globals(), stack(sys.getrecursionlimit())[2:])
if sys.platform == 'ios': # Apple iOS
_gc_getobjects = _getobjects
def _getobjects(): # PYCHOK expected
# avoid Pythonista3/Python 3+ crash
return tuple(o for o in _gc_getobjects() if not _isNULL(o))
try: # only used to get referents of
# iterators, but gc.get_referents()
# returns () for dict...-iterators
from gc import get_referents as _getreferents
except ImportError:
def _getreferents(unused):
return () # sorry, no refs
# sys.getsizeof() new in Python 2.6
_getsizeof = sys.getsizeof # overridden below
_getsizeof_excls = () # types not sys.getsizeof'd
try: # str intern()
_intern = intern
except NameError: # no intern() in Python 3+
def _intern(val):
return val
# 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 _classof(obj, dflt=None):
'''Return the object's class object.
'''
return getattr(obj, '__class__', dflt)
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 a.startswith('__'):
a = '_' + c.__name__ + a
if hasattr(obj, a):
s.setdefault(a, getattr(obj, a))
# assume __slots__ tuple-like is holding the values
# yield slots, _Slots(s) # _keys(s) ... REMOVED,
# see _Slots.__doc__ further below
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 hasattr(obj, a) and a not in excl:
yield a, getattr(obj, a)
def _getsizeof_excls_add(typ):
'''Add another type to the tuple of types to be
excluded from sys.getsizeof due to errors.
'''
global _getsizeof_excls
if typ and typ not in _getsizeof_excls:
_getsizeof_excls += (typ,)
def _infer_dict(obj):
'''Return True for likely dict object via duck typing.
'''
for attrs in (('items', 'keys', 'values'), # 'update',
('iteritems', 'iterkeys', 'itervalues')):
attrs += '__len__', 'get', 'has_key'
if all(_callable(getattr(obj, a, None)) for a in attrs):
return True
return False
def _isbuiltin2(obj):
'''Return True for builtins like Python 2.
'''
# range is no longer a built-in in Python 3+
return isbuiltin(obj) or obj in _builtins2
def _iscell(obj):
'''Return True if obj is a cell as used in a closure.
'''
return isinstance(obj, _cell_type)
def _isdictclass(obj):
'''Return True for known dict objects.
'''
c = _classof(obj)
return c and c.__name__ in _dict_classes.get(c.__module__, ())
def _isframe(obj):
'''Return True for a stack frame object.
'''
try: # safe isframe(), see pympler.muppy
return isframe(obj)
except ReferenceError:
return False
def _isnamedtuple(obj):
'''Named tuples are identified via duck typing:
<http://www.gossamer-threads.com/lists/python/dev/1142178>
'''
return isinstance(obj, tuple) and hasattr(obj, '_fields')
def _isNULL(obj):
'''Prevent asizeof(all=True, ...) crash.
Sizing gc.get_objects() crashes in Pythonista3 with
Python 3.5.1 on iOS due to 1-tuple (<Null>,) object,
see <http://forum.omz-software.com/user/mrjean1>.
'''
return isinstance(obj, tuple) and len(obj) == 1 \
and repr(obj) == '(<NULL>,)'
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)))
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 _moduleof(obj, dflt=''):
'''Return the object's module name.
'''
return getattr(obj, '__module__', dflt)
def _nameof(obj, dflt=''):
'''Return the name of an object.
'''
return getattr(obj, '__name__', dflt)
def _objs_opts_x(objs, all=None, **opts):
'''Return given or 'all' objects
and the remaining options.
'''
if objs: # given objects
t = objs
x = False
elif all in (False, None):
t = ()
x = True
elif all is True: # 'all' objects
t = _getobjects()
x = True
else:
raise ValueError('invalid option: %s=%r' % ('all', all))
return t, opts, x
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, **print3options):
'''Formatted print to sys.stdout or given stream.
*print3options* -- some keyword arguments, like Python 3+ print.
'''
if print3options: # like Python 3+
f = print3options.get('file', None) or sys.stdout
if args:
f.write(fmt % args)
else:
f.write(fmt)
f.write(print3options.get('end', linesep))
if print3options.get('flush', False):
f.flush()
elif args:
print(fmt % args)
else:
print(fmt)
def _refs(obj, named, *attrs, **kwds):
'''Return specific attribute objects of an object.
'''
if named:
_N = _NamedRef
else:
def _N(_, o):
return o
for a in attrs: # cf. inspect.getmembers()
if hasattr(obj, a):
yield _N(a, getattr(obj, a))
if kwds: # kwds are _dir2() args
for a, o in _dir2(obj, **kwds):
yield _N(a, o)
def _repr(obj, clip=80):
'''Clip long repr() string.
'''
try: # safe repr()
r = repr(obj).replace(linesep, '\\n')
except Exception:
r = 'N/A'
if len(r) > clip > 0:
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 referents functions
def _cell_refs(obj, named):
try: # handle 'empty' cells
o = obj.cell_contents
if named:
o = _NamedRef('cell_contents', o)
yield o
except (AttributeError, ValueError):
pass
def _class_refs(obj, named):
'''Return specific referents of a class object.
'''
return _refs(obj, named, '__class__', '__doc__', '__mro__',
'__name__', '__slots__', '__weakref__',
'__dict__') # __dict__ last
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.
'''
try:
if named:
for k, v in _items(obj):
s = str(k)
yield _NamedRef('[K] ' + s, k)
yield _NamedRef('[V] ' + s + ': ' + _repr(v), v)
else:
for k, v in _items(obj):
yield k
yield v
except (KeyError, ReferenceError, TypeError) as x:
warnings.warn("Iterating '%s': %r" % (_classof(obj), x))
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__', '__closure__',
pref='func_', excl=('func_globals',))
def _gen_refs(obj, named):
'''Return the referent(s) of a generator (expression) object.
'''
# only some gi_frame attrs
f = getattr(obj, 'gi_frame', None)
return _refs(f, named, 'f_locals', 'f_code')
# do not yield any items to keep generator intact
# for r in _refs(f, named, 'f_locals', 'f_code'):
# yield r
# for r in obj:
# yield r
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 _namedtuple_refs(obj, named):
'''Return specific referents of obj-as-sequence and slots but exclude dict.
'''
for r in _refs(obj, named, '__class__', slots='__slots__'):
yield r
for r in obj:
yield r
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, '__doc__', '__mro__', '__name__',
'__slots__', '__weakref__', '__dict__')
def _weak_refs(obj, unused): # named unused for PyChecker
'''Return weakly referent object.
'''
try: # ignore 'key' of KeyedRef
return (obj(),)
except Exception: # XXX ReferenceError
return ()
_all_refs = (None, _cell_refs, _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, _namedtuple_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_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
# REMOVED, see _Slots.__doc__
# 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_lens = (None, _len, _len_bytearray, _len_code, _len_dict,
_len_frame, _len_int, _len_iter, _len_list,
_len_module, _len_set, _len_slice, _len_struct,
_len_unicode) # _len_array, _len_numpy, _len_slots