I was comparing the sizes of empty class and empty function in Python with the following code (Python 3.12.3).
class EmptyClass:
pass
def empty_func():
pass
print(f"Class size: {sys.getsizeof(EmptyClass)}")
print(f"Instance size: {sys.getsizeof(EmptyClass())}")
print(f"Function size: {sys.getsizeof(empty_func)}")
# Check the memory requirements of obj methods
def get_mem_size(obj):
mem = 0
for name in dir(obj):
attr = getattr(obj, name)
mem += sys.getsizeof(attr)
return mem
print(f"Class dir size: {get_mem_size(EmptyClass)}")
print(f"Function dir size: {get_mem_size(empty_func)}")
which resulted in the following output
Class size: 1704
Instance size: 48
Function size: 160
Class dir size: 2185
Function dir size: 12287
Trying to understand why empty class takes so much space I stumbled upon this answer. I would expect that the class size should be equal to the size of class variables and methods (which I test with dir(obj)
). However, I get that class size is 1704
while memory footprint from dir
is 2185
. Why this is the case?
The more general question would be, what components contribute to the empty class size in Python and how to explicitly calculate the memory footprint from the components?