Skip to main content

Overview

Python provides specialized allocators for different types of memory:
  1. Raw Memory - System allocator wrappers
  2. Object Memory - Python object allocator
  3. Type-Specific - Per-type allocation
Never mix allocators! Memory allocated with PyMem_Malloc must be freed with PyMem_Free, not free() or PyObject_Free.

Allocation Domains

Raw Domain

For general-purpose buffers, no thread state required:
Example:

Mem Domain

For Python buffers and general-purpose memory:
Example:

Object Domain

For Python objects only:
Free-Threaded Builds: Only use PyObject_* functions for Python objects. Use PyMem_* or standard C allocators for buffers.
Example:

Type Allocators

PyType_GenericAlloc

Allocate memory for a type instance.
PyTypeObject*
required
Type object
Py_ssize_t
required
Number of items (0 for fixed-size types)
Returns: Allocated object, or NULL on error Example:

PyObject_Init

Initialize an allocated object. Example:

PyObject_InitVar

Initialize variable-sized object.

PyObject_New / PyObject_NewVar

Macros combining allocation and initialization. Example:

Garbage Collector Allocators

For types participating in garbage collection:

PyObject_GC_New

Allocate GC-tracked object. Example:

PyObject_GC_Track

Start tracking object for garbage collection. Call after object is fully initialized.

PyObject_GC_UnTrack

Stop tracking object. Call in deallocation before clearing references.

PyObject_GC_Del

Deallocate GC-tracked object. Complete GC Example:

Memory Errors

PyErr_NoMemory

Set MemoryError exception. Always returns NULL for convenience. Example:

Best Practices

Match Allocators and Deallocators
Never use standard C library functions directly on Python objects:
Check all allocations:
Clean up on error:

Allocation Customization

Custom Allocators

You can override Python’s allocators:
Domains:
  • PYMEM_DOMAIN_RAW - Raw memory
  • PYMEM_DOMAIN_MEM - Python memory
  • PYMEM_DOMAIN_OBJ - Python objects

See Also

Type Objects

Defining custom types

Reference Counting

Managing object lifetimes

Memory Management

Advanced memory management

Exception Handling

Handling memory errors