0
$\begingroup$

What is the reason for this behavior? Usually, in other programming languages, it is either 4/8 bytes, if I am correct.

$\endgroup$
0

1 Answer 1

2
$\begingroup$

A boolean value can be represented with just one bit, but are usually four or eight bytes long in most statically typed languages because dealing with values smaller than the register size (four or eight bytes) can be inconvenient. But Python is object-oriented and dynamically typed, meaning that every value is an object and that every value carries information about its type. So you need a lot of metadata you otherwise wouldn't need.

Looking at Python' source code, you'll see that bools are actually implemented as long integers having the values 0 or 1. And "long objects" are defined as follows:

typedef struct _PyLongValue {
    uintptr_t lv_tag; /* Number of digits, sign and flags */
    digit ob_digit[1];
} _PyLongValue;

struct _longobject {
    PyObject_HEAD
    _PyLongValue long_value;
};

PyObject_HEAD is an alias for PyObject, defined as:

typedef struct {
    Py_ssize_t ob_refcnt;   /* object reference count */
    PyTypeObject* ob_type;  /* object type */
};

If we sum the sizes of all the structs' members, we get 28 bytes in total; 8 for ob_refcnt, 8 for ob_type, 8 for lv_tag and 4 for ob_digit[1].

Isn't using 28 bytes for a single boolean wasteful? Probably not since memory allocators allocate memory in chunks to reduce bookkeeping. I haven't checked, but I guess that the smallest chunk Python can allocate is 32 bytes. So it doesn't matter if the object is one byte or 28 bytes. Furthermore, there will never be more than two boolean values in the runtime since every reference to true and every reference to false points to the same object.

$\endgroup$
1
  • 2
    $\begingroup$ Most of this is specific to CPython. There is no reason to assume that every implementation of Python must use the same encoding. Certainly, there is nothing in the Python language specification which requires it. I am willing to bet that at least GraalPython does not use the same encoding. $\endgroup$ Commented Oct 28, 2023 at 8:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.