tags:

views:

170

answers:

4

Is there anyway i can know how much bytes taken by particular variable in python. E.g; lets say i have

int = 12
print (type(int))

it will print

<class 'int'>

But i wanted to know how many bytes it has taken on memory? is it possible?

+8  A: 

You can find the functionality you are looking for here (in sys.getsizeof - Python 2.6 and up).

Also: don't shadow the int builtin!

import sys
myint = 12
print sys.getsizeof(myint)
ChristopheD
is it really giving the size of myint it is returning 14, as far as i know int take 4 bytes, i think its returning the size of whole object, can i just know the size of only "INT"
itsaboutcode
From the docs: `getsizeof` calls the object’s `__sizeof__` method and adds an additional garbage collector overhead if the object is managed by the garbage collector.
Tim Pietzcker
itsaboutcode: Do you want to leave the Python realm? What question do you *really* want to answer? If you want 4 as the answer, then `def sizeof(o): return 4`.
kaizer.se
Do you want to figure out whether the Python instance is a 32 or 64 bits one?
fviktor
And int is an object. There is nothing smaller in the python realm that you can get the size of. If you want the raw machine int, you may have to drop down into C (or Java, or C#, depending on your python).
jcdyer
Thanks all, basically i am learning python these days and in order to do so i am solving problem set from C++ book. So there was this problem which was asking for this, i know how you can do this in C++ or C but i was looking for it python. Thanks all and now i got what you can do within python.
itsaboutcode
If you want to store *many* of int or another C-like datatype, using a minimum of bytes, you can use the `array` class from the array module.
kaizer.se
+4  A: 

In Python >= 2.6 you can use sys.getsizeof.

Alex Barrett
A: 

You could also take a look at Pympler, especially its asizeof module, which unlike sys.getsizeof works with Python >=2.2.

PiotrLegnica
+2  A: 

if you want to know size of int, you can use struct

>>> import struct
>>> struct.calcsize("i")
4

otherwise, as others already pointed out, use getsizeof (2.6). there is also a recipe you can try.