In C, we can find the size of an
char, etc. I want to know how to get size of objects like a string, integer, etc. in Python.
Related question: How many bytes per element are there in a Python list (tuple)?
I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.
Just use the sys.getsizeof function defined in the
Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
defaultargument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a
getsizeofcalls the object’s
__sizeof__method and adds an additional garbage collector overhead if the object is managed by the garbage collector.
Usage example, in python 3.0:
>>> import sys >>> x = 2 >>> sys.getsizeof(x) 24 >>> sys.getsizeof(sys.getsizeof) 32 >>> sys.getsizeof('this') 38 >>> sys.getsizeof('this also') 48
If you are in python < 2.6 and don't have
sys.getsizeof you can use this extensive module instead. Never used it though.