Python does not have char or byte types to store single characters or 8-bit integers. You can use strings of length 1 to represent characters or 8-bit integers.
In Python, the space occupied by each character in the string is bit. (Recommended learning: Python video tutorial)
>>> import sys >>> sys.getsizeof('') 37 >>> sys.getsizeof('a') 38
It can be seen that the null character occupies 37 bytes, and the string 'a' with a length of 1 occupies 38 bytes of memory. After one more character a, there is one more byte.
Internally in Python, string is implemented like this
typedef struct { PyObject_VAR_HEAD long ob_shash; int ob_sstate; char ob_sval[1]; /* Invariants: * ob_sval contains space for 'ob_size+1' elements. * ob_sval[ob_size] == 0. * ob_shash is the hash of the string or -1 if not computed yet. * ob_sstate != 0 iff the string object is in stringobject.c's * 'interned' dictionary; in this case the two references * from 'interned' to this object are *not counted* in ob_refcnt. */ } PyStringObject;
Each char is stored in ob_sval, accounting for 8 bits in size. The remaining 36 bytes mainly come from the macro PyObject_VAR_HEAD. In fact, python's string implementation also uses a global variable called *interned, which can Storing strings of length 0 or 1, that is, char, can save space and speed up.
In fact, there are neither pointers nor "naked data structures" (non-objects) in python, even most Simple integers are implemented in this way
typedef struct { PyObject_HEAD long ob_ival; } PyIntObject;
In short, this design satisfies Python's design philosophy of "everything is an object♂" and "everything is as simple as possible".
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of What are the data types that python does not support?. For more information, please follow other related articles on the PHP Chinese website!