Python __sizeof__ method
The __sizeof__
method in Python is a special dunder method that returns an object’s size in bytes, offering insight into its memory footprint. Integral for memory optimization, it measures internal storage, excluding garbage collection overhead. This article explores its functionality, limitations, and practical uses in depth.
1. What is the __sizeof__
Method?
The __sizeof__
method calculates the memory size of an object’s core structure, invoked via obj.__sizeof__()
.
- Syntax:
def __sizeof__(self)
, returns an integer. - Default: Provided by
object
for built-in types. - Scope: Measures instance data, not referenced objects.
Technical Note: Introduced in Python 2.6, it’s distinct from sys.getsizeof()
, which includes GC overhead.
2. How __sizeof__
Works: A Basic Example
It reveals object size in bytes.
Script:
x = 100
print(x.__sizeof__())
Output:
28
Explanation: __sizeof__
reports the memory used by the integer 100
(typically 28 bytes on 64-bit systems).
3. Comparing with sys.getsizeof()
It differs from sys.getsizeof()
in scope.
Aspect | __sizeof__ |
sys.getsizeof() |
---|---|---|
Scope | Core object | Includes GC overhead |
Use | Type-specific | General-purpose |
Customizable | Yes | No |
Example:
import sys
x = [1, 2, 3]
print(x.__sizeof__())
print(sys.getsizeof(x))
Output:
80
88
Note: sys.getsizeof()
adds GC tracking overhead.
4. Why Use __sizeof__
?
It aids in memory analysis:
Benefit | Description |
---|---|
Insight | Reveals memory footprint. |
Optimization | Guides data structure choice. |
Comparison | Evaluates type efficiency. |
Customization | Allows size overrides. |
Analogy: __sizeof__
is like a tape measure—sizing up an object’s raw space requirements.
5. Practical Applications
A. Built-in Types
Measure standard objects.
print((42).__sizeof__())
print((3.14).__sizeof__())
print(("hello").__sizeof__())
Output:
28
24
54
Use Case: Type comparison.
B. Collections Comparison
Optimize data structures.
lst = [1, 2, 3, 4, 5]
tup = (1, 2, 3, 4, 5)
print(lst.__sizeof__())
print(tup.__sizeof__())
Output:
96
80
Benefit: Tuples save memory due to immutability.
C. Custom Objects
Define size manually.
class Data:
def __init__(self, x):
self.x = x
def __sizeof__(self):
return 100 # Custom size
d = Data(42)
print(d.__sizeof__())
Output:
100
Use Case: Memory modeling.
6. Advanced Insights
Aspect | Behavior | Notes |
---|---|---|
Exclusions | No references | Lists exclude element sizes. |
Platform | Varies | Depends on architecture. |
Recursion | Manual | Custom for nested objects. |
Example (Nested Size):
class Container:
def __init__(self, items):
self.items = items
def __sizeof__(self):
return object.__sizeof__(self) + sum(item.__sizeof__() for item in self.items)
c = Container([1, 2, 3])
print(c.__sizeof__())
Output:
164 <!-- Varies; base + 3 * 28 -->
Tip: Use sys.getsizeof()
for total size.
7. Golden Rules for Using __sizeof__
- ✅ Know Limits: Excludes GC, references.
- ✅ Use Sys: Pair with
sys.getsizeof()
. - ✅ Compare: Test alternatives.
- ❌ Don’t Assume: Sizes vary by platform.
- ❌ Don’t Overuse: Simple checks suffice.
8. Conclusion
The __sizeof__
method is a key tool for assessing an object’s memory footprint in Python, aiding in memory optimization and performance tuning. While limited to core size, it complements sys.getsizeof()
—offering precision when customized. Mastering __sizeof__
sharpens your memory management skills.
Final Tip: "Think of __sizeof__
as your object’s weigh-in—measuring its bare essentials for the memory scale."
Comments
Post a Comment