Skip to main content

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

Check if object is a type object. Returns: 1 if type, 0 otherwise

PyType_CheckExact

Check if object is exactly type (not a subclass). Returns: 1 if exact match, 0 otherwise

Py_IS_TYPE

Check if object’s type is exactly type. Example:

PyObject_TypeCheck

Check if object is of type or subtype. Example:

Type Operations

PyType_IsSubtype

Check if type a is a subtype of type b.
PyTypeObject*
required
Potential subtype
PyTypeObject*
required
Potential supertype
Returns: 1 if a is subtype of b, 0 otherwise

PyType_Ready

Initialize a type object, filling in necessary fields.
Call PyType_Ready() before using a custom type object. Usually done in module initialization.
Returns: 0 on success, -1 on error

PyType_GetName

Get the short name of the type. Returns: New reference to string

PyType_GetQualName

Get the qualified name of the type. Returns: New reference to string

Defining Custom Types

Basic Type Definition

To define a new Python type in C:

Type Object Structure

PyTypeObject Fields

Key fields in PyTypeObject:
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__ implementation
reprfunc
__str__ implementation
PyMethodDef*
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 subclassed
  • Py_TPFLAGS_HEAPTYPE - Type allocated on heap
  • Py_TPFLAGS_HAVE_GC - Type participates in garbage collection

Adding Methods

Method Definitions

Adding Members

Direct Attribute Access

Member types:
  • T_INT - C int
  • T_LONG - C long
  • T_DOUBLE - C double
  • T_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