Skip to content

Commit

Permalink
Size namedtuple values
Browse files Browse the repository at this point in the history
This change includes values when sizing a namedtuple. Before this values were
ignored:

  >>> from pympler import asizeof
  >>> import collections
  >>> Point = collections.namedtuple('Point', ('x', 'y'))
  >>>
  >>> print(asizeof.asized(Point(x=11, y=22), detail=1).format())
  Point(x=11, y=22) size=136 flat=72
      __slots__ size=64 flat=64
      __class__ size=0 flat=0

Now values appear like a tuple's do:

  >>> print(asizeof.asized(Point(x=11, y=22), detail=1).format())
  Point(x=11, y=22) size=184 flat=72
      __slots__ size=64 flat=64
      11 size=24 flat=24
      22 size=24 flat=24
      __class__ size=0 flat=0
  >>> print(asizeof.asized((11, 22), detail=1).format())
  (11, 22) size=120 flat=72
      11 size=24 flat=24
      22 size=24 flat=24

Fixes pympler#35

The modified namedtuple test also passes:

  $ python test/runtest.py --verbose=3 test/asizeof
  • Loading branch information
Chris Klaiber committed Jun 24, 2016
1 parent b43488c commit f7e1573
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
7 changes: 5 additions & 2 deletions pympler/asizeof.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,9 +638,12 @@ def _cell_refs(obj, named):


def _namedtuple_refs(obj, named):
'''Return slots but exclude dict
'''Return specific referents of obj-as-sequence and slots but exclude dict.
'''
return _refs(obj, named, '__class__', slots='__slots__')
for r in _refs(obj, named, '__class__', slots='__slots__'):
yield r
for r in obj:
yield r


def _gen_refs(obj, named):
Expand Down
3 changes: 2 additions & 1 deletion test/asizeof/test_asizeof.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,14 +307,15 @@ def inner():
self.assertTrue(size_closure >= size_data, (size_closure, size_data))

def test_namedtuple(self):
'''Test namedtuple __dict__ property isn't included
'''Test values are included but namedtuple __dict__ isn't.
'''
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
point = Point(x=11, y=22)
size = asizeof.asized(point, detail=1)
refs = [ref.name for ref in size.refs]
self.assertTrue('__dict__' not in refs, refs)
self.assertTrue('11' in refs, refs)


class FunctionTest(unittest.TestCase):
Expand Down

0 comments on commit f7e1573

Please sign in to comment.