Skip to main content

Objects/methodobject.c

Source:

cpython 3.14 @ ab2d84fe1023/Objects/methodobject.c

Objects/methodobject.c implements PyCFunctionObject and PyCMethodObject, which wrap C function pointers as callable Python objects. Every built-in function (len, print, range) and every method defined via PyMethodDef uses one of these types.

Map

LinesSymbolRole
1-80PyCFunction_NewEx, PyCMethod_NewConstructors
81-200PyCFunction_Call, method_callCalling conventions dispatch
201-350PyCFunction_GET_FUNCTION, PyCFunction_GET_FLAGSAccessor macros
351-500tp_repr, tp_richcompare, tp_hashSlots for built-in function type
501-600PyMethodDef registration, PyCFunctionObject type defType object

Reading

Calling conventions

PyMethodDef.ml_flags selects the calling convention:

FlagSignatureNotes
METH_VARARGSf(self, args)Classic; args is a tuple
`METH_VARARGSMETH_KEYWORDS`f(self, args, kwargs)
METH_FASTCALLf(self, *args, nargs)C array of PyObject*
`METH_FASTCALLMETH_KEYWORDS`f(self, *args, nargs, kwnames)
METH_NOARGSf(self, NULL)No arguments
METH_Of(self, arg)Exactly one argument
METH_CLASSprependedclassmethod variant
METH_STATICprependedstaticmethod variant

method_call dispatch

// CPython: Objects/methodobject.c:140 method_call
static PyObject *
method_call(PyObject *func, PyObject *args, PyObject *kwargs)
{
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
PyObject *self = PyCFunction_GET_SELF(func);
int flags = PyCFunction_GET_FLAGS(func);

switch (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
case METH_VARARGS:
...
return meth(self, args);
case METH_VARARGS | METH_KEYWORDS:
return ((PyCFunctionWithKeywords)(void(*)(void))meth)(self, args, kwargs);
case METH_FASTCALL | METH_KEYWORDS:
return _PyCFunction_Vectorcall(func, ...);
...
}
}

PyCMethod_New and the __module__ attribute

PyCMethod_New creates a method bound to a specific type (cls), used for METH_CLASS methods. The type is stored in m_ml (the PyMethodDef) and accessible as __self__.__class__.

Vectorcall support

PyCFunctionObject implements the vectorcall protocol (tp_vectorcall). This allows the interpreter to call built-in functions via CALL_INTRINSIC_1 and CALL_BUILTIN_FAST specialized opcodes without creating an intermediate tuple.

gopy notes

The gopy equivalent is objects/method.go. Built-in methods are Go functions wrapped in a Method struct that holds the function pointer and calling convention flags. The vectorcall fast path is approximated by direct Go function calls when the call site is monomorphic.