Over the years I've come to appreciate a real lot how coherent the Python object model is. For example, the callable concept applies to every object that can be invoked, starting by functions. When you define a function, you have an object that is an instance of the types.FunctionType class, a class that has a __call__ method. In contrast, Kotlin has the invokable concept, but this is an extra (the invoke operator) that you can add to your classes, but the basic invokable element, a method/function, is not an instance of a class with an invoke operator. Functions/methods in Kotlin (at the Kotlin language level, then at a JVM or JavaScript runtime things differ) are not objects, we have to get a function reference or a method reference (with the :: syntax) to treat them as objects.
So having in mind that the callable concept applies to normal functions and methods has made me to dive deeper into what I explained in a recent post:
At the C level, all Python objects are represented by the PyObject structure, which points to a PyTypeObject (its type). The type object defines how instances of that type behave.
To make calls fast and avoid creating temporary tuple/dict arguments, CPython uses the vectorcall protocol (Py_TPFLAGS_HAVE_VECTORCALL).
When the interpreter encounters a CALL opcode, it ultimately looks at the target object's type to find its vectorcall entry point:
- Pure Python Functions (PyFunction_Type): The vectorcall pointer points to _PyFunction_Vectorcall. This function extracts the function's PyCodeObject (func->func_code), allocates a new _PyInterpreterFrame on the evaluation stack, and pushes it to _PyEval_EvalFrameDefault.
- Built-in/Native Functions (PyCFunction_Type): Native functions (like math.sqrt or print) are wrapped in a PyCFunctionObject. Their vectorcall pointer points to _PyCFunction_Vectorcall. This function extracts the underlying C function pointer (func->m_ml->ml_meth) and invokes the compiled C code directly.
But, based on the "callable protocol", when the interpreter encounters a CALL opcode, it should check if the type of the object has a __call__ method and invoke it, right? How does this fit with the above? Well, we have to separate language semantics from implementation:
It's a classic example of language semantics vs. implementation details:
At the language level (Python semantics): Everything is an object, and every object that can be invoked implements the callable protocol via __call__. Defining __call__ on function and builtin_function_or_method keeps the object model clean, predictable, and fully inspectable.
At the runtime level (C implementation): The interpreter is allowed to use any shortcut it wants as long as it doesn't break the language semantics. Since invoking fn() is the most critical operation in the language, CPython uses type-checking fast paths (ob_type) to skip the overhead of attribute lookups.
Going deeper:
Looking up __call__ via the attribute resolution mechanism on every function call would carry massive performance overhead. Here is how CPython handles this under the hood and how it fits with the previous explanation.
1. Fast Paths Bypass __call__ Entirely
For pure Python functions (types.FunctionType) and standard C builtins (types.BuiltinFunctionType), CPython completely bypasses the __call__ method lookup.
Even though type(func).__call__ exists at the Python language level (defined on function / PyFunction_Type), the bytecode interpreter does not execute a dictionary lookup for __call__ when you write func().
Instead:
The interpreter checks Py_TYPE(callable).
If it matches &PyFunction_Type or &PyCFunction_Type, it executes the direct fast paths explained previously (allocating a _PyInterpreterFrame or invoking the vectorcall C function pointer directly).
As for custom callables (instances of classes with a __call__ method), the mechanism is also optimized for performance (it's not doing an expensive MRO __call__ search for any object). The structure representing and object's type, PyTypeObject, has 2 fields, tp_call and tp_vectorcall_offset serving different generations of CPython's calling API. tp_vectorcall_offset is used among others for bound methods and functools.partial. tp_call is used for classes that define a __call__ method (and their derived classes). In that case tp_call points to the generic C wrapper that performs the lookup for "__call__" in the object's class dictionary/MRO and invokes it (and so, if the object does not have a tp_call no search is performed at all).
If we have a function: def fn(), we can invoke it normally, via fn(), but also like this: fn.__call__(). The latter invokation form ends up creating the corresponding _PyInterpreterFrame and running fn's code_object in _PyEval_EvalFrameDefault(), but does it through quite a few extra steps. First we have the look up of the __call__ attribute in the fn object, which will find it in the Function class (types.FunctionType). Retrieving it will give us a bound method (types.MethodType), where __self__ is the fn function, and __func__ is the __call__ function. Then, we have the normal invokation of that bound method, that will end up executing the code object for the fn function.