Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty class size in python

Tags:

python

I just trying to know the rationale behind the empty class size in python, In C++ as everyone knows the size of empty class will always shows 1 byte(as far as i have seen) this let the run time to create unique object,and i trying to find out what size of empty class in python:

class Empty:pass # i hope this will create empty class

and when i do

import sys
print ("show",sys.getsizeof(Empty)) # i get 1016

I wonder why the Empty takes this much 1016(bytes)? and also does the value(1016) it returns is this a standard value that never change(mostly) like C++?, Do we expect any zero base class optimization from python interpreter?Is there any way we can reduce the size of am Empty(just for curiosity sake)?

like image 216
RaGa__M Avatar asked Jun 23 '16 11:06

RaGa__M


People also ask

What is the size of empty class?

It is known that size of an empty class is not zero. Generally, it is 1 byte.

What is empty class in Python?

In Python, to write an empty class pass statement is used. pass is a special statement in Python that does nothing. It only works as a dummy statement. However, objects of an empty class can also be created.

What is the memory of an empty class?

An Empty class's object will take only one byte in the memory; since class doesn't have any data member it will take minimum memory storage.

What is the use of empty class?

An empty class could be used as a "token" defining something unique; in certain patterns, you want an implementation-agnostic representation of a unique instance, which has no value to the developer other than its uniqueness.


1 Answers

I assume you are running a 64 bit version of Python 3. On 32 bit Python 3.6 (on Linux), your code prints show 508.

However, that's the size of the class object itself, which inherits quite a lot of things from the base object class. If you instead get the size of an instance of your class the result is much smaller. On my system,

import sys

class Empty(object):
    pass

print("show", sys.getsizeof(Empty()))

output

show 28

which is a lot more compact. :)

FWIW, on Python 2.6.6, sys.getsizeof(Empty) returns 448 for a new-style class, and a measly 44 for an old-style class (one that doesn't inherit from object). sys.getsizeof(Empty()) returns 28 for a new-style class instance and 32 for an old-style.


You can reduce the size of an instance by using __slots__

This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. __slots__ reserves space for the declared variables and prevents the automatic creation of __dict__ and __weakref__ for each instance.

import sys

class Empty(object):
    __slots__ = []

print("show", sys.getsizeof(Empty()))

output

show 8

Please read the docs to understand how to use this feature.

like image 140
PM 2Ring Avatar answered Sep 27 '22 02:09

PM 2Ring