Python __sizeof__() Method

5/5 - (2 votes)

Syntax

object.__sizeof__(self, other)

The Python __sizeof__() method returns the size of the object in bytes. The sys.getsizeof() method internally call’s __sizeof__() and adds some additional byte overhead, e.g., for garbage collection.

Basic Example

The following code snippet creates a list object x with three integers and measures its size in bytes (104) using the x.__sizeof__() method call.

It then measures the size with overhead using sys.getsizeof(x).

>>> import sys
>>> x = [1, 2, 3]
>>> x.__sizeof__()
104
>>> sys.getsizeof(x)
120

Let’s make the list much larger to measure if it has any impact on the size in bytes.

>>> import sys
>>> x = list(range(10000))
>>> x.__sizeof__()
80040
>>> sys.getsizeof(x)
80056

This list is built using the range() function. It has 10000 integers, each needing 8 bytes with a constant overhead of 40 bytes for the list structure, the x.__sizeof__() method call results in 10000 * 8 + 40 = 80040 bytes.

You can see that in both cases, the sys.getsizeof(x) has 16 more bytes than x.__sizeof__() which seems to be the overhead on my particular machine for this particular example.

Overriding __sizeof__()

You can override the __sizeof__() method for your own custom data type by defining the __sizeof__() method with one argument self (that is passed automatically by Python).

import sys

class Data:
    def __sizeof__(self):
        return 42
    
    
x = Data()
print(x.__sizeof__())

The __sizeof__() method returns the integer 42 that was returned by us—not the number of bytes.

Let’s call the sys.getsizeof() method to see if the difference is 16 bytes for the GC overhead!

import sys

class Data:
    def __sizeof__(self):
        return 42
    
    
x = Data()

print(x.__sizeof__())
# 42

print(sys.getsizeof(x))
# 58

References:

Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!