Overview
Type objects (PyTypeObject) define the behavior of Python types. Every Python object has a type, accessible via obj->ob_type or Py_TYPE(obj).
Built-in Type Objects
Python provides type objects for all built-in types:Type Checking
PyType_Check
1 if type, 0 otherwise
PyType_CheckExact
type (not a subclass).
Returns: 1 if exact match, 0 otherwise
Py_IS_TYPE
type.
Example:
PyObject_TypeCheck
Type Operations
PyType_IsSubtype
a is a subtype of type b.
PyTypeObject*
required
Potential subtype
PyTypeObject*
required
Potential supertype
1 if a is subtype of b, 0 otherwise
PyType_Ready
0 on success, -1 on error
PyType_GetName
PyType_GetQualName
Defining Custom Types
Basic Type Definition
To define a new Python type in C:Type Object Structure
PyTypeObject Fields
Key fields inPyTypeObject:
const char*
Type name (should include module name:
"module.TypeName")Py_ssize_t
Size of instance in bytes (
sizeof(YourStruct))Py_ssize_t
Size of variable-length items (0 for fixed-size types)
const char*
Type docstring
unsigned long
Type flags (see below)
newfunc
Object creation function (
__new__)initproc
Object initialization function (
__init__)destructor
Object destruction function
reprfunc
__repr__ implementationreprfunc
__str__ implementationPyMethodDef*
Method definitions
PyMemberDef*
Member (attribute) definitions
PyGetSetDef*
Computed attribute definitions
Type Flags
Common type flags:Py_TPFLAGS_DEFAULT- Default flags (always use)Py_TPFLAGS_BASETYPE- Type can be subclassedPy_TPFLAGS_HEAPTYPE- Type allocated on heapPy_TPFLAGS_HAVE_GC- Type participates in garbage collection
Adding Methods
Method Definitions
Adding Members
Direct Attribute Access
T_INT- C intT_LONG- C longT_DOUBLE- C doubleT_STRING- C string (char*)T_OBJECT- PyObject* (can be NULL)T_OBJECT_EX- PyObject* (raises AttributeError if NULL)T_BOOL- C char (boolean)
Adding Properties
Computed Attributes
Special Methods
Comparison
String Representation
Hash and Equality
Garbage Collection Support
For types containing PyObject* members that may create reference cycles:See Also
Object Protocol
Generic object operations
Memory Allocation
Allocating type instances
Extension Modules
Creating extension modules
Reference Counting
Managing object references
