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)
>>> sys.getsizeof(sys.getsizeof)
>>> sys.getsizeof('hello')
>>> sys.getsizeof('hello world')

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'))
>>> asizeof.asizeof({'foo': 'b', 'bg': 'a'})
>>> asizeof.asizeof({})
>>> asizeof.asizeof({'foo':'bar'})
>>> asizeof.asizeof('foo')
>>> asizeof.asizeof(Bar())
>>> asizeof.asizeof(Bar().__dict__)
>>> A = [1,2,4]
>>> B = rand(10000)
>>> asizeof.asizeof(A)
>>> asizeof.asizeof(B)

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.