How to determine the exact size of the type used by python

>>> sys.getsizeof(int) 436 #? does this mean int occupies 436 bytes . >>> sys.getsizeof(1) 12 #12 bytes for int object, is this the memory requirement. 

I thought int in python is represented by 4 bytes, why does it report 12 bytes

Please explain why it reports 12 bytes when an int uses only 4 bytes.

+6
source share
2 answers

Yes, an int instance takes 12 bytes on your system. Whole elements (for example, any object) have attributes, that is, pointers to other objects that occupy additional memory space outside, used by the eigenvalue of the object. So, 4 bytes for an integer value, 4 bytes for a pointer to __class__ (otherwise Python would not know what type the object belonged to, and how to start resolving attribute names that are inherited from the int class and its parents) and 4 more to count references to objects used by the garbage collector.

The int type takes 436 bytes on your system, which will point to various methods and other attributes of the int class and any other utility information required by Python for the class. The int class is written in C in the standard Python implementation; you can look at the source code and see what is there.

+10
source

From the documentation for sys.getsizeof :

getsizeof() calls the __sizeof__ method of the objects and adds additional garbage collector overhead if the object is managed by the garbage collector.

Perhaps that is why sys.getsizeof(1) gives you 12 bytes. As for your first line, keep in mind that the int object:

 >>> int <type 'int'> 

int is an integer type, not an integer. An integer in python actually takes as many bytes as needed (so you don't have to worry about overflowing), while the type handles all this functionality. I believe that this difference applies only to built-in types, and for user-defined objects, the type itself is probably the same size as an instance of this type.

+2
source

Source: https://habr.com/ru/post/899365/


All Articles