iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐾

How Are Python Objects Represented in Memory? Part 1

に公開

Introduction

During Python development, unlike C or C++, you rarely need to be conscious of memory contents.
In this document, we will experiment and confirm how objects like int and str are actually stored in memory.

Target CPython version:
https://github.com/python/cpython/blob/3.13

Object Memory Address

Using the built-in function id in CPython allows you to obtain the memory address of an object.

Let's actually peek into the memory of a bytes object.
First, create a bytes object and display its address.

import os
print("pid", os.getpid())      # Display the PID of this process

var1 = b"\x01\x0A\x1F\xEF"
addr = id(var1)
print("var1 :", hex(addr))
# Wait until keyboard input to keep the process alive
input("pause")

The output will be something like:

pid 18908
var1 : 0x106d61170
pause

Here, the process will not terminate until keyboard input, so while this Python process is running, we can check the memory corresponding to this process ID.
On macOS, if Xcode is installed, lldb is available, so you can attach to the process with lldb -p <processID> and inspect memory.

In the example above, execute the following command from the terminal:

lldb -p  18908

At this point, you may be asked for administrator privileges.
Next, use the memory read --format hex --size 1 --count 64 *address* command to read the memory contents.

In this example, the result is as follows:

From this memory content, we can confirm the size of the bytes object and its contents.

The 8 bytes underlined in yellow represent the size of the bytes object, and the red underline represents the contents of the bytes object.
To reach this conclusion, we need to examine the PyBytesObject structure.

typedef struct {
    PyObject_VAR_HEAD
    Py_DEPRECATED(3.11) Py_hash_t ob_shash;
    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 byte string or -1 if not computed yet.
     */
} PyBytesObject;

What is stored in ob_sval is the contents of the bytes object, corresponding to the red line.
PyObject_VAR_HEAD is a header common to objects that have a size. Its actual structure can be represented by the PyVarObject structure.

typedef struct {
    PyObject ob_base;
    Py_ssize_t ob_size; /* Number of items in variable part */
} PyVarObject;

Here, ob_size corresponds to the size of the bytes, represented by the yellow line.
PyObject is a header common to all objects, and its structure is as follows:

/* Nothing is actually declared to be a PyObject, but every pointer to
 * a Python object can be cast to a PyObject*.  This is inheritance built
 * by hand.  Similarly every pointer to a variable-size Python object can,
 * in addition, be cast to PyVarObject*.
 */
#ifndef Py_GIL_DISABLED
struct _object {
#if (defined(__GNUC__) || defined(__clang__)) \
        \u0026\u0026 !(defined __STDC_VERSION__ \u0026\u0026 __STDC_VERSION__ \u003e= 201112L)
    // On C99 and older, anonymous union is a GCC and clang extension
    __extension__
#endif
#ifdef _MSC_VER
    // Ignore MSC warning C4201: "nonstandard extension used:
    // nameless struct/union"
    __pragma(warning(push))
    __pragma(warning(disable: 4201))
#endif
    union {
       Py_ssize_t ob_refcnt;
#if SIZEOF_VOID_P \u003e 4
       PY_UINT32_T ob_refcnt_split[2];
#endif
    };
#ifdef _MSC_VER
    __pragma(warning(pop))
#endif

    PyTypeObject *ob_type;
};
#else
// Objects that are not owned by any thread use a thread id (tid) of zero.
// This includes both immortal objects and objects whose reference count
// fields have been merged.
#define _Py_UNOWNED_TID             0

// The shared reference count uses the two least-significant bits to store
// flags. The remaining bits are used to store the reference count.
#define _Py_REF_SHARED_SHIFT        2
#define _Py_REF_SHARED_FLAG_MASK    0x3

// The shared flags are initialized to zero.
#define _Py_REF_SHARED_INIT         0x0
#define _Py_REF_MAYBE_WEAKREF       0x1
#define _Py_REF_QUEUED              0x2
#define _Py_REF_MERGED              0x3

// Create a shared field from a refcnt and desired flags
#define _Py_REF_SHARED(refcnt, flags) (((refcnt) \u003c\u003c _Py_REF_SHARED_SHIFT) + (flags))

struct _object {
    // ob_tid stores the thread id (or zero). It is also used by the GC and the
    // trashcan mechanism as a linked list pointer and by the GC to store the
    // computed "gc_refs" refcount.
    uintptr_t ob_tid;
    uint16_t _padding;
    PyMutex ob_mutex;           // per-object lock
    uint8_t ob_gc_bits;         // gc-related state
    uint32_t ob_ref_local;      // local reference count
    Py_ssize_t ob_ref_shared;   // shared (atomic) reference count
    PyTypeObject *ob_type;
};
#endif

This is very long and complex, but when GIL is enabled (default behavior), the following fields are stored:

Py_ssize_t ob_refcnt;
PyTypeObject *ob_type;

In the experimental environment, both Py_ssize_t and PyTypeObject* are 8 bytes, so the size of PyObject is 16 bytes.

The structure often changes depending on whether the GIL is enabled or disabled, and whether the process is 32-bit or 64-bit. Therefore, this experiment assumes the GIL is enabled.
If the GIL is disabled, or if running with 32-bit Python, the sample code will not work.

Exploring Object Memory Addresses from Python

As mentioned earlier, you can use the built-in function id to get the address of an object, and then use a debugger to explore the object's memory address. However, this trial-and-error process can be time-consuming.

Therefore, using the ctypes library and the struct library from within Python makes it easier to explore memory.

Exploring PyObject

As mentioned earlier, every object stores PyObject information.

Let's verify how this is laid out in memory from Python.

Sample Code and Output

Sample Code

import ctypes, sys

assert sys.version_info.major == 3
assert sys.version_info.minor == 13
assert sys.implementation.name == 'cpython'
assert sys._is_gil_enabled()

# _object
# Nothing is actually declared to be a PyObject, but every pointer to
# a Python object can be cast to a PyObject*. This is inheritance built
# by hand.
# Similarly, every pointer to a variable-size Python object can,
# in addition, be cast to PyVarObject*.
# https://github.com/python/cpython/blob/3.13/Include/object.h
# Assumes GIL is enabled
class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]


def inspect_base(addr):
    # Cast the specified pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type
    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"\u003ccannot cast to py_object: {e}\u003e"
    return {
        "addr": hex(addr),
        "ob_refcnt": ob_refcnt,
        "ob_type": hex(ob_type),
        "type_obj": type_obj
    }

def print_base(name, addr, indent=0):
    res = inspect_base(addr)
    print('------------------------')
    print(" " * indent, "name:", name)
    print(" " * indent, "addr:", res.get('addr'))
    print(" " * indent, "ob_refcnt:", res.get('ob_refcnt'))
    print(" " * indent, "ob_type:", res.get('ob_type'))
    print(" " * indent, "型", res.get('type_obj'))

var1 = b"\x01\x0A\x1F\xEF"
print_base("bytes data", id(var1))

var2 = 1.0
print_base("float", id(var2))

var3 = 1
print_base("int (small)", id(var3))

var4 = 123456789
print_base("int (large)", id(var4))

var5 = "test1"
print_base("string", id(var5))

var6 = ("test1", 1)
print_base("tuple", id(var6))

var7 = ["test1", 1]
print_base("list", id(var7))

var8 = {"test1": 1, "test2": 1024}
print_base("dict", id(var8))

backup = var1
print_base("bytes data (when reference increased)", id(var1))

Output

------------------------
 name: bytes data
 addr: 0x1010024f0
 ob_refcnt: 4
 ob_type: 0x1016583c0
 型 \u003cclass 'bytes'\u003e
------------------------
 name: float
 addr: 0x100f21a30
 ob_refcnt: 3
 ob_type: 0x1016654e0
 型 \u003cclass 'float'\u003e
------------------------
 name: int (small)
 addr: 0x1016904c0
 ob_refcnt: 4294967295
 ob_type: 0x101667ec0
 型 \u003cclass 'int'\u003e
------------------------
 name: int (large)
 addr: 0x100dbf450
 ob_refcnt: 3
 ob_type: 0x101667ec0
 型 \u003cclass 'int'\u003e
------------------------
 name: string
 addr: 0x1010029a0
 ob_refcnt: 5
 ob_type: 0x101674c10
 型 \u003cclass 'str'\u003e
------------------------
 name: tuple
 addr: 0x100f6a640
 ob_refcnt: 3
 ob_type: 0x10166fb80
 型 \u003cclass 'tuple'\u003e
------------------------
 name: list
 addr: 0x100e9f880
 ob_refcnt: 1
 ob_type: 0x1016674c0
 型 \u003cclass 'list'\u003e
------------------------
 name: dict
 addr: 0x10100f180
 ob_refcnt: 1
 ob_type: 0x101669698
 型 \u003cclass 'dict'\u003e
------------------------
 name: bytes data (when reference increased)
 addr: 0x1010024f0
 ob_refcnt: 5
 ob_type: 0x1016583c0
 型 \u003cclass 'bytes'\u003e

The interpretation of this code and output will be explained in the next chapter.

Representing PyObject from an Object Address

PyObject written in C can be represented by a class inheriting from ctypes.Structure.

class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]

It is possible to cast the object's address obtained using id into a class inheriting from ctypes.Structure.

    # Cast the specified pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type

Checking ob_refcnt

ob_refcnt is the reference count, which increases each time a reference is added.
This can be confirmed by comparing the output results for "bytes data" and "bytes data (when reference increased)".

------------------------
 name: bytes data
 addr: 0x1010024f0
 ob_refcnt: 4
 ob_type: 0x1016583c0
 型 \u003cclass 'bytes'\u003e
... (omitted)
------------------------
 name: bytes data (when reference increased)
 addr: 0x1010024f0
 ob_refcnt: 5
 ob_type: 0x1016583c0
 型 \u003cclass 'bytes'\u003e

This shows that by storing var1 in another variable and increasing the reference, ob_refcnt increases.
Now, looking at the output, we notice that the ob_refcnt for var3 = 1 is abnormally large.

...
------------------------
 name: int (small)
 addr: 0x1016904c0
 ob_refcnt: 4294967295
 ob_type: 0x101667ec0
 型 \u003cclass 'int'\u003e
...

This is because small integers are treated as Immortal Objects.
Normally, an object's lifetime is managed by its reference count. However, starting from Python 3.12, the concept of Immortal Objects was introduced.
In CPython, small integers from -5 to 256 are registered as Immortal Objects during initialization.
These very small integers are made Immortal Objects to be shared globally as singletons.

An explanation of Immortal Objects can be found in the following blog post:
Understanding Immortal Objects in Python 3.12: A Deep Dive into Python Internals

Checking ob_type

ob_type is a pointer to PyTypeObject, which represents the Python type.

To convert the address in ob_type to a Python type, perform a cast as follows:

    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"\u003ccannot cast to py_object: {e}\u003e"

The output shows values like \u003cclass 'int'\u003e, confirming the type.

Exploring PyVarObject

Objects that have a size, such as bytes, list, and tuple, contain PyObject_VAR_HEAD.
As mentioned earlier, this is represented by the PyVarObject structure.
Let's examine the contents of PyVarObject through sample code.

Sample Code and Output

Sample Code

import ctypes, sys

assert sys.version_info.major == 3
assert sys.version_info.minor == 13
assert sys.implementation.name == 'cpython'
assert sys._is_gil_enabled()

# _object
# Nothing is actually declared to be a PyObject, but every pointer to
# a Python object can be cast to a PyObject*. This is inheritance built
# by hand.
# Similarly, every pointer to a variable-size Python object can,
# in addition, be cast to PyVarObject*.
# https://github.com/python/cpython/blob/3.13/Include/object.h
# Assumes GIL is enabled
class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]


# PyVarObject
# https://github.com/python/cpython/blob/3.13/Include/object.h#L224
class PyVarObject(ctypes.Structure):
    _fields_ = [
        ("ob_base", PyObject),
        ("ob_size", ctypes.c_ssize_t),
    ]

def inspect_base(addr):
    # Cast the specified pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type
    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"\u003ccannot cast to py_object: {e}\u003e"
    return {
        "addr": hex(addr),
        "ob_refcnt": ob_refcnt,
        "ob_type": hex(ob_type),
        "type_obj": type_obj
    }

def inspect_py_var(addr):
    res = inspect_base(addr)
    obj = ctypes.cast(addr, ctypes.POINTER(PyVarObject)).contents
    res['ob_size'] = obj.ob_size
    return res

def print_py_var(name, addr, indent=0):
    res = inspect_py_var(addr)
    print('------------------------')
    print(" " * indent, "name:", name)
    print(" " * indent, "addr:", res.get('addr'))
    print(" " * indent, "ob_refcnt:", res.get('ob_refcnt'))
    print(" " * indent, "ob_type:", res.get('ob_type'))
    print(" " * indent, "型", res.get('type_obj'))
    print(" " * indent, "ob_size", res.get('ob_size'))

var1 = b"\x01\x0A\x1F\xEF"
print_py_var("bytes data", id(var1))

var2 = ("test1", 1)
print_py_var("tuple", id(var2))

var3 = ["test1", 1, 3]
print_py_var("list", id(var3))

var4 = []
print_py_var("list (empty)", id(var4))

Output

------------------------
 name: bytes data
 addr: 0x10cbfec40
 ob_refcnt: 4
 ob_type: 0x10d24f3c0
 型 \u003cclass 'bytes'\u003e
 ob_size 4
------------------------
 name: tuple
 addr: 0x10cb66640
 ob_refcnt: 3
 ob_type: 0x10d266b80
 型 \u003cclass 'tuple'\u003e
 ob_size 2
------------------------
 name: list
 addr: 0x10cc0b1c0
 ob_refcnt: 1
 ob_type: 0x10d25e4c0
 型 \u003cclass 'list'\u003e
 ob_size 3
------------------------
 name: list (empty)
 addr: 0x10cc09e00
 ob_refcnt: 1
 ob_type: 0x10d25e4c0
 型 \u003cclass 'list'\u003e
 ob_size 0

Representing PyVarObject from an Object Address

PyVarObject written in C can be represented by a class inheriting from ctypes.Structure.

# PyVarObject
# https://github.com/python/cpython/blob/3.13/Include/object.h#L224
class PyVarObject(ctypes.Structure):
    _fields_ = [
        ("ob_base", PyObject),
        ("ob_size", ctypes.c_ssize_t),
    ]

It is possible to cast the object's address obtained using id into a class inheriting from ctypes.Structure.

    obj = ctypes.cast(addr, ctypes.POINTER(PyVarObject)).contents
    res['ob_size'] = obj.ob_size

Checking ob_size

From the output, we can see that the size is stored in ob_size.

Stored Data Output ob_size
b"\x01\x0A\x1F\xEF" 4
("test1", 1) 2
["test1", 1, 3] 3
[] 0

Exploring PyFloatObject

Floating-point types like 1.5 and 8.5e+5 are stored in PyFloatObject.

Sample Code and Output

Sample Code

import ctypes, sys

assert sys.version_info.major == 3
assert sys.version_info.minor == 13
assert sys.implementation.name == 'cpython'
assert sys._is_gil_enabled()

# _object
# Nothing is actually declared to be a PyObject, but every pointer to
# a Python object can be cast to a PyObject*. This is inheritance built
# by hand.
# Similarly, every pointer to a variable-size Python object can,
# in addition, be cast to PyVarObject*.
# https://github.com/python/cpython/blob/3.13/Include/object.h
# Assumes GIL is enabled
class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]


# https://github.com/python/cpython/blob/3.13/Include/cpython/floatobject.h#L5
class PyFloatObject(ctypes.Structure):
    _fields_ = [
        ("head", PyObject),
        ("ob_fval", ctypes.c_double),
    ]

def inspect_base(addr):
    # Cast the specified pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type
    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"\u003ccannot cast to py_object: {e}\u003e"
    return {
        "addr": hex(addr),
        "ob_refcnt": ob_refcnt,
        "ob_type": hex(ob_type),
        "type_obj": type_obj
    }

def inspect_float(addr):
    res = inspect_base(addr)
    obj = ctypes.cast(addr, ctypes.POINTER(PyFloatObject)).contents
    res['ob_fval'] = obj.ob_fval
    return res

def print_float(name, addr, indent=0):
    res = inspect_float(addr)
    print('------------------------')
    print(" " * indent, "name:", name)
    print(" " * indent, "addr:", res.get('addr'))
    print(" " * indent, "ob_refcnt:", res.get('ob_refcnt'))
    print(" " * indent, "ob_type:", res.get('ob_type'))
    print(" " * indent, "Type", res.get('type_obj'))
    print(" " * indent, "ob_fval", res.get('ob_fval'))

var1 = 1.5
print_float("Float: 1.5", id(var1))

var2 = 8.5e+5
print_float("Float: 8.5e+5", id(var2))

Output

------------------------
 name: Float: 1.5
 addr: 0x106815a30
 ob_refcnt: 3
 ob_type: 0x106f534e0
 Type \u003cclass 'float'\u003e
 ob_fval 1.5
------------------------
 name: Float: 8.5e+5
 addr: 0x1066aefb0
 ob_refcnt: 3
 ob_type: 0x106f534e0
 Type \u003cclass 'float'\u003e
 ob_fval 850000.0

Representing PyFloatObject from an Object Address

PyFloatObject written in C can be represented by a class inheriting from ctypes.Structure.

# https://github.com/python/cpython/blob/3.13/Include/cpython/floatobject.h#L5
class PyFloatObject(ctypes.Structure):
    _fields_ = [
        ("head", PyObject),
        ("ob_fval", ctypes.c_double),
    ]

It is possible to cast the object's address obtained using id into a class inheriting from ctypes.Structure.

    obj = ctypes.cast(addr, ctypes.POINTER(PyFloatObject)).contents
    res['ob_fval'] = obj.ob_fval

ob_fval is of type double, so the actual numeric value is stored here.

Exploring PyLongObject

Python integers are represented by the PyLongObject structure.

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;
};

A notable feature of Python integers is that they support arbitrary precision.

To achieve this, lv_tag holds the number of digits and sign information.
ob_digit can be extended by the number specified in lv_tag.

Sample Code and Output

Sample Code

import ctypes, sys, struct

assert sys.version_info.major == 3
assert sys.version_info.minor == 13
assert sys.implementation.name == 'cpython'
assert sys._is_gil_enabled()

# _object
# Nothing is actually declared to be a PyObject, but every pointer to
# a Python object can be cast to a PyObject*. This is inheritance built
# by hand.
# Similarly, every pointer to a variable-size Python object can,
# in addition, be cast to PyVarObject*.
# https://github.com/python/cpython/blob/3.13/Include/object.h
# Assumes GIL is enabled
class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]


# PyLongObject
# https://github.com/python/cpython/blob/3.13/Include/cpython/longintrepr.h#L98
class PyLongObject(ctypes.Structure):
    _fields_ = [
        ("head", PyObject),
        # lv_tag 
        # Lower 2 bits: sign 0:positive 1:Zero 2:negative
        # 3rd bit: for "immortality" flag, currently unused
        # Other bits: number of digits
        ("lv_tag", ctypes.c_void_p)
        # Actually followed by digits, but not defined here because it's variable-length
    ]

def inspect_base(addr):
    # Cast the specified pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type
    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"\u003ccannot cast to py_object: {e}\u003e"
    return {
        "addr": hex(addr),
        "ob_refcnt": ob_refcnt,
        "ob_type": hex(ob_type),
        "type_obj": type_obj
    }

def inspect_int(addr):
    res_base = inspect_base(addr)
    assert res_base.get('type_obj') == int

    obj = ctypes.cast(addr, ctypes.POINTER(PyLongObject)).contents
    sign = obj.lv_tag \u0026 0b11
    flag = obj.lv_tag \u0026 0b100  # unused
    ndigits = obj.lv_tag  \u003e\u003e 3

    # Determine the ctypes type for digit
    fmt_char = {1: 'B', 2: 'H', 4: 'I', 8: 'Q'}
    digit_bytes = (sys.int_info.bits_per_digit + 7) // 8
    if digit_bytes == 2:
        digit_ctype = ctypes.c_uint16
    elif digit_bytes == 4:
        digit_ctype = ctypes.c_uint32
    elif digit_bytes == 8:
        digit_ctype = ctypes.c_uint64
    else:
        raise RuntimeError(f'unexpected digit_bytes {digit_bytes}')
    digits = []
    if ndigits \u003e 0:
        BufType = digit_ctype * ndigits
        buf = BufType.from_address(addr+ctypes.sizeof(PyLongObject))   # Dangerous: assumes address is valid
        mv = memoryview(buf)

        # struct.unpack_from also accepts memoryview
        digits_raw = struct.unpack_from(f'{ndigits}{fmt_char.get(digit_bytes)}', mv, 0)
        for b in digits_raw:
            digits.append(f"0x{b:08x}")
    dict_sign = {
        0: "Positive",
        1: "Zero",
        2: "Negative",
    }
    res = {
        "lv_tag": hex(obj.lv_tag),
        "sign": dict_sign.get(sign),
        "flag": flag,
        "ndigits": ndigits,
        "digit_bytes": digit_bytes,
        "digits": digits
    }
    return res | res_base

def print_int(name, addr, indent=0):
    res = inspect_int(addr)
    print('------------------------')
    print(" " * indent, "name:", name)
    print(" " * indent, "addr:", res.get('addr'))
    print(" " * indent, "ob_refcnt:", res.get('ob_refcnt'))
    print(" " * indent, "ob_type:", res.get('ob_type'))
    print(" " * indent, "Type:", res.get('type_obj'))
    print(" " * indent, "lv_tag:", res.get('lv_tag'))
    print(" " * indent, "sign:", res.get('sign'))
    print(" " * indent, "ndigits:", res.get('ndigits'))
    print(" " * indent, "digits:", res.get('digits'))

var1 = 0
print_int("Integer: 0", id(var1))

var2 = 1
print_int("Integer: 1", id(var2))

var3 = -1
print_int("Integer: -1", id(var3))

var4 = 1024
print_int("Integer: 1024", id(var4))

var5 = 1 \u003c\u003c 30
print_int(f"Integer: {var5}", id(var5))

var6 = 2147483647
print_int(f"Integer: 2147483647", id(var6))

var7 = 4294967295
print_int(f"Integer: 4294967295", id(var7))

var8 = 1 \u003c\u003c (30*2)
print_int(f"Integer: {var8}", id(var8))

Output

------------------------
 name: Integer: 0
 addr: 0x1027c74a0
 ob_refcnt: 4294967295
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x1
 sign: Zero
 ndigits: 0
 digits: []
------------------------
 name: Integer: 1
 addr: 0x1027c74c0
 ob_refcnt: 4294967295
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x8
 sign: Positive
 ndigits: 1
 digits: ['0x00000001']
------------------------
 name: Integer: -1
 addr: 0x1027c7480
 ob_refcnt: 4294967295
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0xa
 sign: Negative
 ndigits: 1
 digits: ['0x00000001']
------------------------
 name: Integer: 1024
 addr: 0x101ef7450
 ob_refcnt: 3
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x8
 sign: Positive
 ndigits: 1
 digits: ['0x00000400']
------------------------
 name: Integer: 1073741824
 addr: 0x10205f2f0
 ob_refcnt: 3
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x10
 sign: Positive
 ndigits: 2
 digits: ['0x00000000', '0x00000001']
------------------------
 name: Integer: 2147483647
 addr: 0x10205f3b0
 ob_refcnt: 3
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x10
 sign: Positive
 ndigits: 2
 digits: ['0x3fffffff', '0x00000001']
------------------------
 name: Integer: 4294967295
 addr: 0x10205c3f0
 ob_refcnt: 3
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x10
 sign: Positive
 ndigits: 2
 digits: ['0x3fffffff', '0x00000003']
------------------------
 name: Integer: 1152921504606846976
 addr: 0x1021611a0
 ob_refcnt: 3
 ob_type: 0x10279eec0
 Type: \u003cclass 'int'\u003e
 lv_tag: 0x18
 sign: Positive
 ndigits: 3
 digits: ['0x00000000', '0x00000000', '0x00000001']

Representing PyLongObject from an Object Address

PyLongObject written in C can be represented by a class inheriting from ctypes.Structure.

class PyLongObject(ctypes.Structure):
    _fields_ = [
        ("head", PyObject),
        # lv_tag 
        # Lower 2 bits: sign 0:positive 1:Zero 2:negative
        # 3rd bit: for "immortality" flag, currently unused
        # Other bits: number of digits
        ("lv_tag", ctypes.c_void_p)
        # Actually followed by digits, but not defined here because it's variable-length
    ]

Originally, one or more digit types follow lv_tag. The method for obtaining digits is described later.

It is possible to cast the object's address obtained using id into a class inheriting from ctypes.Structure.

    obj = ctypes.cast(addr, ctypes.POINTER(PyLongObject)).contents

Checking lv_tag

lv_tag encodes the sign, immortality flag, and the number of digits using different bit positions.

Bit Position Description
Bits 1-2 Sign: 0=Positive, 1=Zero, 2=Negative
Bit 3 Immortality flag (currently unused)
Bits 4+ Number of digits

This can be extracted with the following code:

    sign = obj.lv_tag \u0026 0b11
    flag = obj.lv_tag \u0026 0b100  # unused
    ndigits = obj.lv_tag  \u003e\u003e 3

By comparing the output for var1 = 0, var2 = 1, and var3 = -1, we can confirm the sign values change for Zero, Positive, and Negative.

Checking digits

Digits are organized into chunks of 30 or 15 bits depending on the platform.
Whether it's 30 or 15 bits per digit can be checked with sys.int_info.bits_per_digit.

If it's 30 bits, a digit is stored in a uint32, but only 30 bits are valid.
For numbers exceeding 30 bits, the digits array is extended.
The number of chunks is given by ndigits from lv_tag.

An example of retrieving ndigits items of digit type as uint32:

    fmt_char = {1: 'B', 2: 'H', 4: 'I', 8: 'Q'}
    digit_bytes = (sys.int_info.bits_per_digit + 7) // 8
    if digit_bytes == 2:
        digit_ctype = ctypes.c_uint16
    elif digit_bytes == 4:
        digit_ctype = ctypes.c_uint32
    elif digit_bytes == 8:
        digit_ctype = ctypes.c_uint64
    else:
        raise RuntimeError(f'unexpected digit_bytes {digit_bytes}')
    digits = []
    if ndigits \u003e 0:
        BufType = digit_ctype * ndigits
        buf = BufType.from_address(addr+ctypes.sizeof(PyLongObject))   # Dangerous: assumes address is valid
        mv = memoryview(buf)

        # struct.unpack_from also accepts memoryview
        digits_raw = struct.unpack_from(f'{ndigits}{fmt_char.get(digit_bytes)}', mv, 0)
        for b in digits_raw:
            digits.append(f"0x{b:08x}")

From the output, we can see how actual values are stored in digits:

Value digits
0 [] *sign=Zero
1 [0x00000001] *sign=Positive
-1 [0x00000001] *sign=Negative
1024 ['0x00000400']
Value not representable in 30 bits\u003cbr\u003e1073741824 ['0x00000000', '0x00000001']
2147483647 ['0x3fffffff', '0x00000001']
4294967295 ['0x3fffffff', '0x00000003']
Value not representable in 60 bits\u003cbr\u003e1152921504606846976 ['0x00000000', '0x00000000', '0x00000001']

By splitting values into 30-bit chunks and storing them in digits, arbitrary precision can be achieved.

Exploring PyBytesObject

The Python bytes type is represented by the PyBytesObject structure.

Sample Code and Output

Sample Code

import ctypes, sys, struct

assert sys.version_info.major == 3
assert sys.version_info.minor == 13
assert sys.implementation.name == 'cpython'
assert sys._is_gil_enabled()

# _object
# Nothing is actually declared to be a PyObject, but every pointer to
# a Python object can be cast to a PyObject*. This is inheritance built
# by hand.
# Similarly, every pointer to a variable-size Python object can,
# in addition, be cast to PyVarObject*.
# https://github.com/python/cpython/blob/3.13/Include/object.h
# Assumes GIL is enabled
class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]


# PyVarObject
# https://github.com/python/cpython/blob/3.13/Include/object.h#L224
class PyVarObject(ctypes.Structure):
    _fields_ = [
        ("ob_base", PyObject),
        ("ob_size", ctypes.c_ssize_t),
    ]

# https://github.com/python/cpython/blob/3.13/Include/cpython/bytesobject.h#L5
class PyBytesObject(ctypes.Structure):
    _fields_ = [
        ("head", PyVarObject),
        # ob_shash is the hash of the byte string or -1 if not computed yet.
        # Deprecated since Python 3.11
        ("ob_shash", ctypes.c_ssize_t),
        # Followed by char ob_sval
    ]


def inspect_base(addr):
    # Cast the specified pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type
    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"\u003ccannot cast to py_object: {e}\u003e"
    return {
        "addr": hex(addr),
        "ob_refcnt": ob_refcnt,
        "ob_type": hex(ob_type),
        "type_obj": type_obj
    }

def inspect_byte(addr):
    res_base = inspect_base(addr)
    assert res_base.get('type_obj') == bytes
    obj = ctypes.cast(addr, ctypes.POINTER(PyBytesObject)).contents
    ob_size = obj.head.ob_size
    ob_shash = obj.ob_shash
    data = []
    if ob_size \u003e 0:
        BufType = ctypes.c_ubyte * ob_size
        buf = BufType.from_address(addr+ctypes.sizeof(PyBytesObject))   # Dangerous: assumes address is valid
        mv = memoryview(buf)

        # struct.unpack_from also accepts memoryview
        raw = struct.unpack_from(f'{ob_size}B', mv, 0)
        for b in raw:
            data.append(f"0x{b:02x}")
    res = {
        "ob_size": ob_size,
        "ob_shash": ob_shash,
        "ob_sval": data
    }
    return res | res_base

def print_bytes(name, addr, indent=0):
    res = inspect_byte(addr)
    print('------------------------')
    print(" " * indent, "name:", name)
    print(" " * indent, "addr:", res.get('addr'))
    print(" " * indent, "ob_refcnt:", res.get('ob_refcnt'))
    print(" " * indent, "ob_type:", res.get('ob_type'))
    print(" " * indent, "Type", res.get('type_obj'))
    print(" " * indent, "ob_size", res.get('ob_size'))
    print(" " * indent, "ob_shash", res.get('ob_shash'))
    print(" " * indent, "ob_sval", res.get('ob_sval'))

var1 = b"\x01\x0A\x1F\xEF"
print_bytes("bytes data A", id(var1))

var2 = b"\x01\x0A\x1F\xEE"
print_bytes("bytes data B (different from A)", id(var2))

var3 = b"\x01\x0A\x1F\xEF"
print_bytes("bytes data C (same as A)", id(var3))

var4 = b""
print_bytes("bytes data D (empty)", id(var4))

Output

------------------------
 name: bytes data A
 addr: 0x10761bcc0
 ob_refcnt: 4
 ob_type: 0x107c703c0
 Type \u003cclass 'bytes'\u003e
 ob_size 4
 ob_shash -4882734533440356415
 ob_sval ['0x01', '0x0a', '0x1f', '0xef']
------------------------
 name: bytes data B (different from A)
 addr: 0x10761bde0
 ob_refcnt: 4
 ob_type: 0x107c703c0
 Type \u003cclass 'bytes'\u003e
 ob_size 4
 ob_shash -5159122674606314679
 ob_sval ['0x01', '0x0a', '0x1f', '0xee']
------------------------
 name: bytes data C (same as A)
 addr: 0x10761bcc0
 ob_refcnt: 5
 ob_type: 0x107c703c0
 Type \u003cclass 'bytes'\u003e
 ob_size 4
 ob_shash -4882734533440356415
 ob_sval ['0x01', '0x0a', '0x1f', '0xef']
------------------------
 name: bytes data D (empty)
 addr: 0x107caa4c0
 ob_refcnt: 4294967295
 ob_type: 0x107c703c0
 Type \u003cclass 'bytes'\u003e
 ob_size 0
 ob_shash 0
 ob_sval []

Representing PyBytesObject from an Object Address

PyBytesObject written in C can be represented by a class inheriting from ctypes.Structure.

class PyBytesObject(ctypes.Structure):
    _fields_ = [
        ("head", PyVarObject),
        # ob_shash is the hash of the byte string or -1 if not computed yet.
        # Deprecated since Python 3.11
        ("ob_shash", ctypes.c_ssize_t),
        # Followed by char ob_sval
    ]

After ob_shash, ob_sval continues for PyVarObject.ob_size bytes. The method for retrieving this is described later.

It is possible to cast the object's address obtained using id into a class inheriting from ctypes.Structure.

    obj = ctypes.cast(addr, ctypes.POINTER(PyBytesObject)).contents
    ob_size = obj.head.ob_size
    ob_shash = obj.ob_shash

Checking ob_shash

ob_shash stores the hash value computed from the bytes content.
This value matches the value obtained via var1.__hash__().

Also, within the same process, it matches for identical content, as confirmed by the output.

Data ob_shash Description
b"\x01\x0A\x1F\xEF" -4882734533440356415 Reference data
b"\x01\x0A\x1F\xEE" -5159122674606314679 Different content gives different ob_shash
b"\x01\x0A\x1F\xEF" -4882734533440356415 Same content gives same ob_shash
b"" 0 Empty bytes has ob_shash 0

Note that ob_shash has been deprecated since Python 3.11.

Checking ob_sval

To inspect from Python, read PyVarObject.ob_size bytes starting after ob_shash.

    data = []
    if ob_size \u003e 0:
        BufType = ctypes.c_ubyte * ob_size
        buf = BufType.from_address(addr+ctypes.sizeof(PyBytesObject))   # Dangerous: assumes address is valid
        mv = memoryview(buf)

        # struct.unpack_from also accepts memoryview
        raw = struct.unpack_from(f'{ob_size}B', mv, 0)
        for b in raw:
            data.append(f"0x{b:02x}")

Exploring PyASCIIObject/PyCompactUnicodeObject/PyUnicodeObject

The Python Unicode string type is specified in PEP 393.

When a string (str type) is created, it takes one of three forms depending on the character content and whether it uses a compact representation:

  • PyASCIIObject
    • Strings that contain only ASCII characters (U+0000–U+007F) and use a compact representation
  • PyCompactUnicodeObject
    • Strings that include non-ASCII characters and use a compact representation
  • PyUnicodeObject
    • Non-compact strings (legacy objects)

A "compact representation" means whether the character data immediately follows the base structure in memory.
Objects whose size and maximum character width are known at creation time use the compact representation.
Creating a subclass of str, for example, results in a non-compact representation.

Below are the C structures for PyASCIIObject/PyCompactUnicodeObject/PyUnicodeObject:

typedef struct {
    PyObject_HEAD
    Py_ssize_t length;          /* Number of code points in the string */
    Py_hash_t hash;             /* Hash value; -1 if not set */
    struct {
        unsigned int interned:2;
        unsigned int kind:3;
        unsigned int compact:1;
        unsigned int ascii:1;
        unsigned int statically_allocated:1;
        unsigned int :24;
    } state;
} PyASCIIObject;

typedef struct {
    PyASCIIObject _base;
    Py_ssize_t utf8_length;     /* Number of bytes in utf8, excluding the
                                 * terminating \0. */
    char *utf8;                 /* UTF-8 representation (null-terminated) */
} PyCompactUnicodeObject;

typedef struct {
    PyCompactUnicodeObject _base;
    union {
        void *any;
        Py_UCS1 *latin1;
        Py_UCS2 *ucs2;
        Py_UCS4 *ucs4;
    } data;                     /* Canonical, smallest-form Unicode buffer */
} PyUnicodeObject;

PyCompactUnicodeObject and PyUnicodeObject contain a PyASCIIObject as their header.
The combination of compact and ascii flags in PyASCIIObject determines whether the actual object is PyASCIIObject, PyCompactUnicodeObject, or PyUnicodeObject.

The state fields are summarized as follows:

Field Name Width (bits) Description
interned 2 0: Not interned / 1: Interned / 2: Interned and immortal / 3: Interned+immortal+static\u003cbr\u003eReference
kind 3 1: Py_UCS1 (8 bits, unsigned) 2: Py_UCS2 (16 bits, unsigned) 4: Py_UCS4 (32 bits, unsigned)
compact 1 1: Compact representation (character data follows header directly) / 0: Legacy representation (pointer to separate area)
ascii 1 1: All characters are ASCII (U+0000–U+007F)
statically_allocated 1 1: Allocated in static area (never freed) – for static strings embedded at build time.
(reserved) 24 Reserved (unused)

The following sample code examines PyASCIIObject/PyCompactUnicodeObject/PyUnicodeObject.

Sample Code and Output

Sample Code

import ctypes, sys, struct

assert sys.version_info.major == 3
assert sys.version_info.minor == 13
assert sys.implementation.name == 'cpython'
assert sys._is_gil_enabled()

# _object
# Nothing is actually declared to be a PyObject, but every pointer to
# a Python object can be cast to a PyObject*.  This is inheritance built
# by hand.  Similarly every pointer to a variable-size Python object can,
# in addition, be cast to PyVarObject*.
# https://github.com/python/cpython/blob/3.13/Include/object.h
# Assumes GIL is enabled
class PyObject(ctypes.Structure):
    _fields_ = [
        ("ob_refcnt", ctypes.c_ssize_t),
        ("ob_type", ctypes.c_void_p),
    ]


# https://github.com/python/cpython/blob/3.13/Include/cpython/unicodeobject.h#L50
class PyASCIIObject(ctypes.Structure):
    _fields_ = [
        ("head", PyObject),
        ("length", ctypes.c_ssize_t),
        ("hash", ctypes.c_ssize_t),
        ("interned", ctypes.c_uint, 2),
        ("kind", ctypes.c_uint, 3),
        ("compact", ctypes.c_uint, 1),
        ("ascii", ctypes.c_uint, 1),
        ("statically_allocated", ctypes.c_uint, 1),
        ("_pad", ctypes.c_uint, 24),
    ]
class PyCompactUnicodeObject(ctypes.Structure):
    _fields_ = [
        ("_base", PyASCIIObject),
        ("utf8_length", ctypes.c_ssize_t),
        ("utf8", ctypes.c_void_p),
    ]
class PyUnicodeObject(ctypes.Structure):
    _fields_ = [
        ("_base", PyCompactUnicodeObject),
        ("data_any", ctypes.c_void_p),  # union data
    ]

def inspect_base(addr):
    # Cast the given pointer to the PyObject type
    obj = ctypes.cast(addr, ctypes.POINTER(PyObject)).contents
    ob_refcnt = obj.ob_refcnt
    ob_type = obj.ob_type
    try:
        type_obj = ctypes.cast(ob_type, ctypes.py_object).value
    except Exception as e:
        type_obj = f"<cannot cast to py_object: {e}>"
    return {
        "addr": hex(addr),
        "ob_refcnt": ob_refcnt,
        "ob_type": hex(ob_type),
        "type_obj": type_obj
    }

def inspect_unicode(addr):
    SSTATE_NAMES = {
        0: "NOT_INTERNED", 1: "INTERNED",
        2: "INTERNED_IMMORTAL", 3: "INTERNED_IMMORTAL_STATIC",
    }
    res_base = inspect_base(addr)
    assert issubclass(res_base.get('type_obj'), str)
    obj = ctypes.cast(addr, ctypes.POINTER(PyASCIIObject)).contents
    compact = obj.compact
    ascii = obj.ascii
    length = obj.length
    kind = obj.kind
    res = {
        "hash": obj.hash,
        "statically_allocated": obj.statically_allocated,
        "interned": SSTATE_NAMES.get(obj.interned),
        "compact": compact,
        "ascii": ascii,
        "kind": kind,
        "length": length,
    }
    # Determine the data start address based on the form
    if compact and ascii:
        # compact ASCII: data directly after header
        data_addr = addr + ctypes.sizeof(PyASCIIObject)
    elif compact and not ascii:
        # compact: data exists right after PyCompactUnicodeObject
        data_addr = addr + ctypes.sizeof(PyCompactUnicodeObject)
        compact_obj = ctypes.cast(addr, ctypes.POINTER(PyCompactUnicodeObject)).contents
        res['utf8'] = compact_obj.utf8
        res['utf8_length'] = compact_obj.utf8_length
    else:
        # legacy (mainly subclasses)
        # data is in a separate area
        legacy_obj = ctypes.cast(addr, ctypes.POINTER(PyUnicodeObject)).contents
        data_addr = legacy_obj.data_any
    # Element width (bytes/code point)
    if kind == 1:
        Elem = ctypes.c_uint8
    elif kind == 2:
        Elem = ctypes.c_uint16
    elif kind == 4:
        Elem = ctypes.c_uint32
    else:
        raise RuntimeError(f"unexpected kind={kind}")
    fmt_char = {1: 'B', 2: 'H', 4: 'I'}[kind]       # 1/2/4 byte unsigned integer

    BufType = Elem * length
    buf = BufType.from_address(data_addr)   # Dangerous: assumes address is valid
    mv = memoryview(buf)

    # struct.unpack_from can also take a memoryview
    data_array = struct.unpack_from(f'{length}{fmt_char}', mv, 0)
    display_data = []
    for b in data_array:
        disp_b = {1: f"0x{b:02x}", 2: f"0x{b:04x}", 4: f"0x{b:08x}"}[kind]
        display_data.append(disp_b)
    res["data"] = display_data
    return res | res_base

def print_unicode(name, addr, indent=0):
    res = inspect_unicode(addr)
    print('------------------------')
    print(" " * indent, "name:", name)
    print(" " * indent, "addr:", res.get('addr'))
    print(" " * indent, "ob_refcnt:", res.get('ob_refcnt'))
    print(" " * indent, "ob_type:", res.get('ob_type'))
    print(" " * indent, "type:", res.get('type_obj'))
    print(" " * indent, "length:", res.get('length'))
    print(" " * indent, "hash:", res.get('hash'))
    print(" " * indent, "interned:", res.get('interned'))
    print(" " * indent, "kind:", res.get('kind'))
    print(" " * indent, "compact:", res.get('compact'))
    print(" " * indent, "ascii:", res.get('ascii'))
    print(" " * indent, "statically_allocated:", res.get('statically_allocated'))
    print(" " * indent, "utf8:", res.get('utf8'))
    print(" " * indent, "utf8_length:", res.get('utf8_length'))
    print(" " * indent, "data:", res.get('data'))

class S(str):
    pass

# kind=1
var1 = '12345abcd'
print_unicode(f"compact representation (ASCII): {var1}", id(var1))

# kind=2
var2 = '12345あabcd'
print_unicode(f"compact representation (non-ASCII, Py_UCS2): {var2}", id(var2))

# kind=4
var3 = '12345😊abcd'
print_unicode(f"compact representation (non-ASCII, Py_UCS3): {var3}", id(var3))

# not compact; data is taken from a separate area
var4 = S('xxxxx')
print_unicode(f"legacy representation: {var4}", id(var4))

# The following result should match var1's hash
var5 = '12345abcd'
print_unicode(f"Check if hash matches var1: {var5}", id(var5))
print("var5.__hash__() result", var5.__hash__())

# Empty string
# Check interned:INTERNED_IMMORTAL_STATIC and statically_allocated=1
var6 = ''
print_unicode("empty string", id(var6))

# Check interned:INTERNED_IMMORTAL_STATIC and statically_allocated=1
var7 = 'a'
print_unicode(f"ASCII single character A {var7}", id(var7))

# Check interned:INTERNED_IMMORTAL_STATIC and statically_allocated=1
var8 = '+'
print_unicode(f"ASCII single character B {var8}", id(var8))


var9 = "".join(['12345','abcd'])
print_unicode(f"Same content as var1 created with join {var9}", id(var9))
assert var1 == var9
assert var1 is not var9

var10 = sys.intern(var9)
print_unicode(f"Intern var9 {var10}", id(var10))
assert var1 == var10
assert var1 is var10


# Example that stores values in utf8 and utf8_length
# When PyUnicode_AsUTF8() / PyUnicode_AsUTF8AndSize() is called, the UTF-8 representation is generated/cached and stored in utf8 and utf8_length
# The following code calls PyUnicode_AsUTF8 on var2
PyUnicode_AsUTF8 = ctypes.pythonapi.PyUnicode_AsUTF8
PyUnicode_AsUTF8.restype = ctypes.c_char_p
PyUnicode_AsUTF8.argtypes = [ctypes.py_object]
ptr = PyUnicode_AsUTF8(var2)
print_unicode(f"Execute PyUnicode_AsUTF8 on non-ASCII compact representation: {var2}", id(var2))

Output

------------------------
 name: compact representation (ASCII): 12345abcd
 addr: 0x10abc45f0
 ob_refcnt: 3
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 9
 hash: 2615342146504599036
 interned: INTERNED
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 0
 utf8: None
 utf8_length: None
 data: ['0x31', '0x32', '0x33', '0x34', '0x35', '0x61', '0x62', '0x63', '0x64']
------------------------
 name: compact representation (non-ASCII, Py_UCS2): 12345あabcd
 addr: 0x10aa95470
 ob_refcnt: 3
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 10
 hash: 4408673876641812804
 interned: NOT_INTERNED
 kind: 2
 compact: 1
 ascii: 0
 statically_allocated: 0
 utf8: None
 utf8_length: 0
 data: ['0x0031', '0x0032', '0x0033', '0x0034', '0x0035', '0x3042', '0x0061', '0x0062', '0x0063', '0x0064']
------------------------
 name: compact representation (non-ASCII, Py_UCS3): 12345😊abcd
 addr: 0x10ab1c650
 ob_refcnt: 3
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 10
 hash: 3692057203771936543
 interned: NOT_INTERNED
 kind: 4
 compact: 1
 ascii: 0
 statically_allocated: 0
 utf8: None
 utf8_length: 0
 data: ['0x00000031', '0x00000032', '0x00000033', '0x00000034', '0x00000035', '0x0001f60a', '0x00000061', '0x00000062', '0x00000063', '0x00000064']
------------------------
 name: legacy representation: xxxxx
 addr: 0x10abd4350
 ob_refcnt: 1
 ob_type: 0x7fb36e034020
 type: <class '__main__.S'>
 length: 5
 hash: -5889910096978768055
 interned: NOT_INTERNED
 kind: 1
 compact: 0
 ascii: 1
 statically_allocated: 0
 utf8: None
 utf8_length: None
 data: ['0x78', '0x78', '0x78', '0x78', '0x78']
------------------------
 name: Check if hash matches var1: 12345abcd
 addr: 0x10abc45f0
 ob_refcnt: 4
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 9
 hash: 2615342146504599036
 interned: INTERNED
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 0
 utf8: None
 utf8_length: None
 data: ['0x31', '0x32', '0x33', '0x34', '0x35', '0x61', '0x62', '0x63', '0x64']
var5.__hash__() result 2615342146504599036
------------------------
 name: empty string
 addr: 0x10b2217d8
 ob_refcnt: 4294967295
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 0
 hash: 0
 interned: INTERNED_IMMORTAL_STATIC
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 1
 utf8: None
 utf8_length: None
 data: []
------------------------
 name: ASCII single character A a
 addr: 0x10b22c0f8
 ob_refcnt: 4294967295
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 1
 hash: -6101737322674053506
 interned: INTERNED_IMMORTAL_STATIC
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 1
 utf8: None
 utf8_length: None
 data: ['0x61']
------------------------
 name: ASCII single character B +
 addr: 0x10b22b6d8
 ob_refcnt: 4294967295
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 1
 hash: 5732640424058351956
 interned: INTERNED_IMMORTAL_STATIC
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 1
 utf8: None
 utf8_length: None
 data: ['0x2b']
------------------------
 name: Same content as var1 created with join 12345abcd
 addr: 0x10abac9f0
 ob_refcnt: 1
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 9
 hash: -1
 interned: NOT_INTERNED
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 0
 utf8: None
 utf8_length: None
 data: ['0x31', '0x32', '0x33', '0x34', '0x35', '0x61', '0x62', '0x63', '0x64']
------------------------
 name: Intern var9 12345abcd
 addr: 0x10abc45f0
 ob_refcnt: 5
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 9
 hash: 2615342146504599036
 interned: INTERNED
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 0
 utf8: None
 utf8_length: None
 data: ['0x31', '0x32', '0x33', '0x34', '0x35', '0x61', '0x62', '0x63', '0x64']
------------------------
 name: Plain reference to var9 is not interned 12345abcd
 addr: 0x10abac9f0
 ob_refcnt: 2
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 9
 hash: 2615342146504599036
 interned: NOT_INTERNED
 kind: 1
 compact: 1
 ascii: 1
 statically_allocated: 0
 utf8: None
 utf8_length: None
 data: ['0x31', '0x32', '0x33', '0x34', '0x35', '0x61', '0x62', '0x63', '0x64']
------------------------
 name: Execute PyUnicode_AsUTF8 on non-ASCII compact representation: 12345あabcd
 addr: 0x10aa95470
 ob_refcnt: 3
 ob_type: 0x10b200c10
 type: <class 'str'>
 length: 10
 hash: 4408673876641812804
 interned: NOT_INTERNED
 kind: 2
 compact: 1
 ascii: 0
 statically_allocated: 0
 utf8: 4472899952
 utf8_length: 12
 data: ['0x0031', '0x0032', '0x0033', '0x0034', '0x0035', '0x3042', '0x0061', '0x0062', '0x0063', '0x0064']

Representing PyASCIIObject/PyCompactUnicodeObject/PyUnicodeObject from an Object Address

PyASCIIObject/PyCompactUnicodeObject/PyUnicodeObject written in C
can be expressed as classes inheriting from ctypes.Structure.

class PyASCIIObject(ctypes.Structure):
    _fields_ = [
        ("head", PyObject),
        ("length", ctypes.c_ssize_t),
        ("hash", ctypes.c_ssize_t),
        ("interned", ctypes.c_uint, 2),
        ("kind", ctypes.c_uint, 3),
        ("compact", ctypes.c_uint, 1),
        ("ascii", ctypes.c_uint, 1),
        ("statically_allocated", ctypes.c_uint, 1),
        ("_pad", ctypes.c_uint, 24),
    ]
class PyCompactUnicodeObject(ctypes.Structure):
    _fields_ = [
        ("_base", PyASCIIObject),
        ("utf8_length", ctypes.c_ssize_t),
        ("utf8", ctypes.c_void_p),
    ]
class PyUnicodeObject(ctypes.Structure):
    _fields_ = [
        ("_base", PyCompactUnicodeObject),
        ("data_any", ctypes.c_void_p),  # union data
    ]

From the address of the object obtained with id(), first cast it to PyASCIIObject.

Then, depending on the ascii and compact flags, cast further as needed:

    obj = ctypes.cast(addr, ctypes.POINTER(PyASCIIObject)).contents
    compact = obj.compact
    ascii = obj.ascii
    length = obj.length
    kind = obj.kind
    ... omitted ...
    # Determine the data start address based on the form
    if compact and ascii:
        # compact ASCII: data directly after header
        data_addr = addr + ctypes.sizeof(PyASCIIObject)
    elif compact and not ascii:
        # compact: data exists right after PyCompactUnicodeObject
        data_addr = addr + ctypes.sizeof(PyCompactUnicodeObject)
        compact_obj = ctypes.cast(addr, ctypes.POINTER(PyCompactUnicodeObject)).contents
        res['utf8'] = compact_obj.utf8
        res['utf8_length'] = compact_obj.utf8_length
    else:
        # legacy (mainly subclasses)
        # data is in a separate area
        legacy_obj = ctypes.cast(addr, ctypes.POINTER(PyUnicodeObject)).contents
        data_addr = legacy_obj.data_any

### Example of Extracting Character Data

For `PyASCIIObject`/`PyCompactUnicodeObject`, the character data start address is immediately after the structure. For `PyUnicodeObject`, `PyUnicodeObject.data_any` is the start address.

The byte length of one character varies depending on `PyASCIIObject.kind`:

| `kind` | Bytes per character |
|---:|---:|
| 1 | 1 |
| 2 | 2 |
| 4 | 4 |

Since the string length is `PyASCIIObject.length`, the character data ranges from the start address to `start_address + PyASCIIObject.length * bytes_per_character`.

The following code retrieves character data from the start address:

```python
    # Element width (bytes/code point)
    if kind == 1:
        Elem = ctypes.c_uint8
    elif kind == 2:
        Elem = ctypes.c_uint16
    elif kind == 4:
        Elem = ctypes.c_uint32
    else:
        raise RuntimeError(f"unexpected kind={kind}")
    fmt_char = {1: 'B', 2: 'H', 4: 'I'}[kind]       # 1/2/4 byte unsigned integer

    BufType = Elem * length
    buf = BufType.from_address(data_addr)   # Dangerous: assumes address is valid
    mv = memoryview(buf)

    # struct.unpack_from can also take a memoryview
    data_array = struct.unpack_from(f'{length}{fmt_char}', mv, 0)
    display_data = []
    for b in data_array:
        disp_b = {1: f"0x{b:02x}", 2: f"0x{b:04x}", 4: f"0x{b:08x}"}[kind]
        display_data.append(disp_b)
    res["data"] = display_data

Output Examples

Declaration length kind Character data
var1 = '12345abcd' 9 1 ['0x31', '0x32', '0x33', '0x34', '0x35', '0x61', '0x62', '0x63', '0x64']
var2 = '12345あabcd' 10 2 ['0x0031', '0x0032', '0x0033', '0x0034', '0x0035', '0x3042', '0x0061', '0x0062', '0x0063', '0x0064']
var3 = '12345😊abcd' 10 4 ['0x00000031', '0x00000032', '0x00000033', '0x00000034', '0x00000035', '0x0001f60a', '0x00000061', '0x00000062', '0x00000063', '0x00000064']

Checking hash

The hash field stores the hash value computed from the string contents.
This value matches that obtained with var1.__hash__().

Also, within the same process, identical content yields the same hash, as can be seen from the output results.

Data hash Description
var1 = '12345abcd' 2615342146504599036 Reference data
var2 = '12345あabcd' 4408673876641812804 Different value from var1
var5 = '12345abcd' 2615342146504599036 Same value as var1

Checking interned and statically_allocated

Python has a concept of string interning.

Interned strings can be compared using pointer equality (is) for the same value.
This is used to optimize dictionary and attribute lookups.
Also, empty strings and "single-character Latin-1 strings" like "a" or "+" are statically registered as singletons at process startup.

The following table shows how interned and statically_allocated behave in the output examples.

Declaration interned statically_
allocated
Description
var1 = '12345abcd' INTERNED 0 An ASCII literal may become an interned string in some cases
var2 = '12345あabcd' NOT_INTERNED 0 A non-ASCII literal does not become an interned string
var6 = '' INTERNED_IMMORTAL_STATIC 1 Statically registered as a singleton at initialization
var7 = 'a' INTERNED_IMMORTAL_STATIC 1 Statically registered as a singleton at initialization
var8 = '+' INTERNED_IMMORTAL_STATIC 1 Statically registered as a singleton at initialization
var9 = "".join(['12345','abcd']) NOT_INTERNED 0 Same value as var1, but created with join; not an interned string.
Same value as var1 but different pointer.
assert var1 == var9
assert var1 is not var9
var10 = sys.intern(var9) INTERNED 0 Using sys.intern makes it an interned string.
Matches var1 in both value and pointer.
assert var1 == var10
assert var1 is var10

Checking utf8 and utf8_length

PyCompactUnicodeObject has utf8 and utf8_length fields.

However, simply creating a non-ASCII compact string like var2 = '12345あabcd' does not set these fields.
The UTF-8 representation is generated and cached only when PyUnicode_AsUTF8() / PyUnicode_AsUTF8AndSize() is called, and then stored in utf8 and utf8_length.
To call PyUnicode_AsUTF8() / PyUnicode_AsUTF8AndSize() from Python, do the following:

PyUnicode_AsUTF8 = ctypes.pythonapi.PyUnicode_AsUTF8
PyUnicode_AsUTF8.restype = ctypes.c_char_p
PyUnicode_AsUTF8.argtypes = [ctypes.py_object]
ptr = PyUnicode_AsUTF8(var2)
print_unicode(f"Execute PyUnicode_AsUTF8 on non-ASCII compact representation: {var2}", id(var2))

The tuple, list, and dict Types

Covered in the latter part.

References

Discussion