项目作者: liran-funaro

项目描述 :
Traversal over Python's objects sub-tree and calculating the total size of the sub-tree (deep size).
高级语言: Python
项目地址: git://github.com/liran-funaro/objsize.git
创建时间: 2018-12-11T15:09:52Z
项目社区:https://github.com/liran-funaro/objsize

开源协议:GNU General Public License v3.0

下载


objsize

Coverage Status Downloads

The objsize Python package allows for the exploration and
measurement of an object’s complete memory usage in bytes, including its
child objects. This process, often referred to as deep size calculation,
is achieved through Python’s internal Garbage Collection (GC) mechanism.

The objsize package is designed to ignore shared objects, such as
None, types, modules, classes, functions, and lambdas, because they
are shared across many instances. One of the key performance features of
objsize is that it avoids recursive calls, ensuring a faster and
safer execution.

Key Features

  • Traverse objects’ subtree
  • Calculates the size of objects, including nested objects (deep size), in bytes
  • Exclude non-exclusive objects
  • Exclude specified objects subtree
  • Provides flexibility by allowing users to define custom handlers for:
    • Object’s size calculation
    • Object’s referents (i.e., its children)
    • Object filter (skip specific objects)

Documentation

objsize Traversal over Python’s objects subtree and calculating the total size of the subtree (deep size).

Install

  1. pip install objsize==0.7.1

Basic Usage

Calculate the size of the object including all its members in bytes.

  1. >>> import objsize
  2. >>> objsize.get_deep_size(dict(arg1='hello', arg2='world'))
  3. 340

It is possible to calculate the deep size of multiple objects by passing
multiple arguments:

  1. >>> objsize.get_deep_size(['hello', 'world'], dict(arg1='hello', arg2='world'), {'hello', 'world'})
  2. 628

Complex Data

objsize can calculate the size of an object’s entire subtree in
bytes regardless of the type of objects in it, and its depth.

Here is a complex data structure, for example, that include a self
reference:

  1. my_data = list(range(3)), list(range(3, 6))
  2. class MyClass:
  3. def __init__(self, x, y):
  4. self.x = x
  5. self.y = y
  6. self.d = {'x': x, 'y': y, 'self': self}
  7. def __repr__(self):
  8. return f"{self.__class__.__name__}()"
  9. my_obj = MyClass(*my_data)

We can calculate my_obj deep size, including its stored data.

  1. >>> objsize.get_deep_size(my_obj)
  2. 724

We might want to ignore non-exclusive objects such as the ones stored in
my_data.

  1. >>> objsize.get_deep_size(my_obj, exclude=[my_data])
  2. 384

Or simply let objsize detect that automatically:

  1. >>> objsize.get_exclusive_deep_size(my_obj)
  2. 384

Non Shared Functions or Classes

objsize filters functions, lambdas, and classes by default since
they are usually shared among many objects. For example:

  1. >>> method_dict = {"identity": lambda x: x, "double": lambda x: x*2}
  2. >>> objsize.get_deep_size(method_dict)
  3. 232

Some objects, however, as illustrated in the above example, have unique
functions not shared by other objects. Due to this, it may be useful to
count their sizes. You can achieve this by providing an alternative
filter function.

  1. >>> objsize.get_deep_size(method_dict, filter_func=objsize.shared_object_filter)
  2. 986

Notes:

Special Cases

Some objects handle their data in a way that prevents Python’s GC from
detecting it. The user can supply a special way to calculate the actual
size of these objects.

Case 1: torch

Using a simple calculation of the object size won’t work for
torch.Tensor.

  1. >>> import torch
  2. >>> objsize.get_deep_size(torch.rand(200))
  3. 72

So the user can define its own size calculation handler for such cases:

  1. import objsize
  2. import sys
  3. import torch
  4. def get_size_of_torch(o):
  5. # `objsize.safe_is_instance` catches `ReferenceError` caused by `weakref` objects
  6. if objsize.safe_is_instance(o, torch.Tensor):
  7. return sys.getsizeof(o) + (o.element_size() * o.nelement())
  8. else:
  9. return sys.getsizeof(o)

Then use it as follows:

  1. >>> objsize.get_deep_size(
  2. ... torch.rand(200),
  3. ... get_size_func=get_size_of_torch
  4. ... )
  5. 872

The above approach may neglect the object’s internal structure. The user
can help objsize to find the object’s hidden storage by supplying it
with its own referent and filter functions:

  1. import objsize
  2. import gc
  3. import torch
  4. def get_referents_torch(*objs):
  5. # Yield all native referents
  6. yield from gc.get_referents(*objs)
  7. for o in objs:
  8. # If the object is a torch tensor, then also yield its storage
  9. if type(o) == torch.Tensor:
  10. yield o.untyped_storage()
  11. # `torch.dtype` is a common object like Python's types.
  12. MySharedObjects = (*objsize.SharedObjectOrFunctionType, torch.dtype)
  13. def filter_func(o):
  14. return not objsize.safe_is_instance(o, MySharedObjects)

Then use these as follows:

  1. >>> objsize.get_deep_size(
  2. ... torch.rand(200),
  3. ... get_referents_func=get_referents_torch,
  4. ... filter_func=filter_func
  5. ... )
  6. 928

Case 2: weakref

Using a simple calculation of the object size won’t work for
weakref.proxy.

  1. >>> from collections import UserList
  2. >>> o = UserList([0]*100)
  3. >>> objsize.get_deep_size(o)
  4. 1032
  5. >>> import weakref
  6. >>> o_ref = weakref.proxy(o)
  7. >>> objsize.get_deep_size(o_ref)
  8. 72

To mitigate this, you can provide a method that attempts to fetch the
proxy’s referents:

  1. import weakref
  2. import gc
  3. def get_weakref_referents(*objs):
  4. yield from gc.get_referents(*objs)
  5. for o in objs:
  6. if type(o) in weakref.ProxyTypes:
  7. try:
  8. yield o.__repr__.__self__
  9. except ReferenceError:
  10. pass

Then use it as follows:

  1. >>> objsize.get_deep_size(o_ref, get_referents_func=get_weakref_referents)
  2. 1104

After the referenced object will be collected, then the size of the
proxy object will be reduced.

  1. >>> del o
  2. >>> gc.collect()
  3. >>> # Wait for the object to be collected
  4. >>> objsize.get_deep_size(o_ref, get_referents_func=get_weakref_referents)
  5. 72

Object Size Settings

To avoid repeating the input settings when handling the special cases
above, you can use the ObjSizeSettings class.

  1. >>> torch_objsize = objsize.ObjSizeSettings(
  2. ... get_referents_func=get_referents_torch,
  3. ... filter_func=filter_func,
  4. ... )
  5. >>> torch_objsize.get_deep_size(torch.rand(200))
  6. 928
  7. >>> torch_objsize.get_deep_size(torch.rand(300))
  8. 1328

See ObjSizeSettings for the
list of configurable parameters.

Traversal

A user can implement its own function over the entire subtree using the
traversal method, which traverses all the objects in the subtree.

  1. >>> for o in objsize.traverse_bfs(my_obj):
  2. ... print(o)
  3. ...
  4. MyClass()
  5. {'x': [0, 1, 2], 'y': [3, 4, 5], 'd': {'x': [0, 1, 2], 'y': [3, 4, 5], 'self': MyClass()}}
  6. [0, 1, 2]
  7. [3, 4, 5]
  8. {'x': [0, 1, 2], 'y': [3, 4, 5], 'self': MyClass()}
  9. 2
  10. 1
  11. 0
  12. 5
  13. 4
  14. 3

Similar to before, non-exclusive objects can be ignored.

  1. >>> for o in objsize.traverse_exclusive_bfs(my_obj):
  2. ... print(o)
  3. ...
  4. MyClass()
  5. {'x': [0, 1, 2], 'y': [3, 4, 5], 'd': {'x': [0, 1, 2], 'y': [3, 4, 5], 'self': MyClass()}}
  6. {'x': [0, 1, 2], 'y': [3, 4, 5], 'self': MyClass()}

Alternative

Pympler also supports
determining an object deep size via pympler.asizeof(). There are two
main differences between objsize and pympler.

  1. objsize has additional features:
    • Traversing the object subtree: iterating all the object’s
      descendants one by one.
    • Excluding non-exclusive objects. That is, objects that are also
      referenced from somewhere else in the program. This is true for
      calculating the object’s deep size and for traversing its
      descendants.
  2. objsize has a simple and robust implementation with significantly
    fewer lines of code, compared to pympler. The Pympler
    implementation uses recursion, and thus have to use a maximal depth
    argument to avoid reaching Python’s max depth. objsize, however,
    uses BFS which is more efficient and simple to follow. Moreover, the
    Pympler implementation carefully takes care of any object type.
    objsize archives the same goal with a simple and generic
    implementation, which has fewer lines of code.

License: BSD-3

Copyright (c) 2006-2025, Liran Funaro.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
  3. Neither the name of the copyright holder nor the
    names of its contributors may be used to endorse or promote products
    derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.