get object size in python

How to Get Size of Object in Python

Python allows you to store data in different formats such as strings, integers, dictionary, lists, tuples and so on. Each of these data types is an object that occupies a definite space in memory during execution. Sometimes you may need to determine object size to make sure your code is not consuming too many resources. Sometimes you may also need to get object size, if you want to make sure that you replace a data of one type with data that is of same size. In this article, we will learn how to get size of object in Python.


How to Get Size of Object in Python

Python offers sys. getsizeof() function that returns the size of any object, in bytes. Here is the syntax of getsizeof() function.

sys.getsizeof(object[, default])

It will return correct object size of all types of built-in data objects, but may not apply to third-party data structures.

However, please note, getsizeof() function returns only the size of object and not of the objects it refers to. Also it will not give complete size of nested objects like nested list, or dictionaries. Basically, it refers to the __sizeof__ method and adds an additional overhead for garbage collector, in case it is managed by garbage collector.

Here are the some examples to determine the size of object in Python.

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
12
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('hello')
26
>>> sys.getsizeof('hello world')
32

If you want to get size of nested and complex objects, you can use asizeof function in Pympler package. Here is how to install it.

$ pip install Pympler

It works for your custom created objects also as shown below.

>>> asizeof.asizeof(tuple('abc'))
200
>>> asizeof.asizeof({'foo': 'b', 'bg': 'a'})
300
>>> asizeof.asizeof({})
180
>>> asizeof.asizeof({'foo':'bar'})
240
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
342
>>> asizeof.asizeof(Bar().__dict__)
280
>>> A = [1,2,4]
>>> B = rand(10000)
>>> asizeof.asizeof(A)
156
>>> asizeof.asizeof(B)
60096

In this article, we have learnt a couple of simple ways to get size of object in Python.

Also read:

How to Import from Parent Folder in Python
How to Attach Event to Dynamic Elements in JavaScript
How to Get Subset of JS Object
How to Close Current Tab in Browser
How to Get ID of Element That Fired Event

Leave a Reply

Your email address will not be published. Required fields are marked *