Overview
Python provides specialized allocators for different types of memory:- Raw Memory - System allocator wrappers
- Object Memory - Python object allocator
- Type-Specific - Per-type allocation
Allocation Domains
Raw Domain
For general-purpose buffers, no thread state required:Mem Domain
For Python buffers and general-purpose memory:Object Domain
For Python objects only:Type Allocators
PyType_GenericAlloc
PyTypeObject*
required
Type object
Py_ssize_t
required
Number of items (0 for fixed-size types)
NULL on error
Example:
PyObject_Init
PyObject_InitVar
PyObject_New / PyObject_NewVar
Garbage Collector Allocators
For types participating in garbage collection:PyObject_GC_New
PyObject_GC_Track
PyObject_GC_UnTrack
PyObject_GC_Del
Memory Errors
PyErr_NoMemory
MemoryError exception. Always returns NULL for convenience.
Example:
Best Practices
Match Allocators and Deallocators
Check all allocations:
Clean up on error:
Allocation Customization
Custom Allocators
You can override Python’s allocators:PYMEM_DOMAIN_RAW- Raw memoryPYMEM_DOMAIN_MEM- Python memoryPYMEM_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
