1.. highlight:: c
2
3.. _call:
4
5Call Protocol
6=============
7
8CPython supports two different calling protocols:
9*tp_call* and vectorcall.
10
11The *tp_call* Protocol
12----------------------
13
14Instances of classes that set :c:member:`~PyTypeObject.tp_call` are callable.
15The signature of the slot is::
16
17    PyObject *tp_call(PyObject *callable, PyObject *args, PyObject *kwargs);
18
19A call is made using a tuple for the positional arguments
20and a dict for the keyword arguments, similarly to
21``callable(*args, **kwargs)`` in Python code.
22*args* must be non-NULL (use an empty tuple if there are no arguments)
23but *kwargs* may be *NULL* if there are no keyword arguments.
24
25This convention is not only used by *tp_call*:
26:c:member:`~PyTypeObject.tp_new` and :c:member:`~PyTypeObject.tp_init`
27also pass arguments this way.
28
29To call an object, use :c:func:`PyObject_Call` or another
30:ref:`call API <capi-call>`.
31
32
33.. _vectorcall:
34
35The Vectorcall Protocol
36-----------------------
37
38.. versionadded:: 3.9
39
40The vectorcall protocol was introduced in :pep:`590` as an additional protocol
41for making calls more efficient.
42
43As rule of thumb, CPython will prefer the vectorcall for internal calls
44if the callable supports it. However, this is not a hard rule.
45Additionally, some third-party extensions use *tp_call* directly
46(rather than using :c:func:`PyObject_Call`).
47Therefore, a class supporting vectorcall must also implement
48:c:member:`~PyTypeObject.tp_call`.
49Moreover, the callable must behave the same
50regardless of which protocol is used.
51The recommended way to achieve this is by setting
52:c:member:`~PyTypeObject.tp_call` to :c:func:`PyVectorcall_Call`.
53This bears repeating:
54
55.. warning::
56
57   A class supporting vectorcall **must** also implement
58   :c:member:`~PyTypeObject.tp_call` with the same semantics.
59
60A class should not implement vectorcall if that would be slower
61than *tp_call*. For example, if the callee needs to convert
62the arguments to an args tuple and kwargs dict anyway, then there is no point
63in implementing vectorcall.
64
65Classes can implement the vectorcall protocol by enabling the
66:const:`Py_TPFLAGS_HAVE_VECTORCALL` flag and setting
67:c:member:`~PyTypeObject.tp_vectorcall_offset` to the offset inside the
68object structure where a *vectorcallfunc* appears.
69This is a pointer to a function with the following signature:
70
71.. c:type:: PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)
72
73- *callable* is the object being called.
74- *args* is a C array consisting of the positional arguments followed by the
75   values of the keyword arguments.
76   This can be *NULL* if there are no arguments.
77- *nargsf* is the number of positional arguments plus possibly the
78   :const:`PY_VECTORCALL_ARGUMENTS_OFFSET` flag.
79   To get the actual number of positional arguments from *nargsf*,
80   use :c:func:`PyVectorcall_NARGS`.
81- *kwnames* is a tuple containing the names of the keyword arguments;
82   in other words, the keys of the kwargs dict.
83   These names must be strings (instances of ``str`` or a subclass)
84   and they must be unique.
85   If there are no keyword arguments, then *kwnames* can instead be *NULL*.
86
87.. c:macro:: PY_VECTORCALL_ARGUMENTS_OFFSET
88
89   If this flag is set in a vectorcall *nargsf* argument, the callee is allowed
90   to temporarily change ``args[-1]``. In other words, *args* points to
91   argument 1 (not 0) in the allocated vector.
92   The callee must restore the value of ``args[-1]`` before returning.
93
94   For :c:func:`PyObject_VectorcallMethod`, this flag means instead that
95   ``args[0]`` may be changed.
96
97   Whenever they can do so cheaply (without additional allocation), callers
98   are encouraged to use :const:`PY_VECTORCALL_ARGUMENTS_OFFSET`.
99   Doing so will allow callables such as bound methods to make their onward
100   calls (which include a prepended *self* argument) very efficiently.
101
102To call an object that implements vectorcall, use a :ref:`call API <capi-call>`
103function as with any other callable.
104:c:func:`PyObject_Vectorcall` will usually be most efficient.
105
106
107.. note::
108
109   In CPython 3.8, the vectorcall API and related functions were available
110   provisionally under names with a leading underscore:
111   ``_PyObject_Vectorcall``, ``_Py_TPFLAGS_HAVE_VECTORCALL``,
112   ``_PyObject_VectorcallMethod``, ``_PyVectorcall_Function``,
113   ``_PyObject_CallOneArg``, ``_PyObject_CallMethodNoArgs``,
114   ``_PyObject_CallMethodOneArg``.
115   Additionally, ``PyObject_VectorcallDict`` was available as
116   ``_PyObject_FastCallDict``.
117   The old names are still defined as aliases of the new, non-underscored names.
118
119
120Recursion Control
121.................
122
123When using *tp_call*, callees do not need to worry about
124:ref:`recursion <recursion>`: CPython uses
125:c:func:`Py_EnterRecursiveCall` and :c:func:`Py_LeaveRecursiveCall`
126for calls made using *tp_call*.
127
128For efficiency, this is not the case for calls done using vectorcall:
129the callee should use *Py_EnterRecursiveCall* and *Py_LeaveRecursiveCall*
130if needed.
131
132
133Vectorcall Support API
134......................
135
136.. c:function:: Py_ssize_t PyVectorcall_NARGS(size_t nargsf)
137
138   Given a vectorcall *nargsf* argument, return the actual number of
139   arguments.
140   Currently equivalent to::
141
142      (Py_ssize_t)(nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET)
143
144   However, the function ``PyVectorcall_NARGS`` should be used to allow
145   for future extensions.
146
147   .. versionadded:: 3.8
148
149.. c:function:: vectorcallfunc PyVectorcall_Function(PyObject *op)
150
151   If *op* does not support the vectorcall protocol (either because the type
152   does not or because the specific instance does not), return *NULL*.
153   Otherwise, return the vectorcall function pointer stored in *op*.
154   This function never raises an exception.
155
156   This is mostly useful to check whether or not *op* supports vectorcall,
157   which can be done by checking ``PyVectorcall_Function(op) != NULL``.
158
159   .. versionadded:: 3.8
160
161.. c:function:: PyObject* PyVectorcall_Call(PyObject *callable, PyObject *tuple, PyObject *dict)
162
163   Call *callable*'s :c:type:`vectorcallfunc` with positional and keyword
164   arguments given in a tuple and dict, respectively.
165
166   This is a specialized function, intended to be put in the
167   :c:member:`~PyTypeObject.tp_call` slot or be used in an implementation of ``tp_call``.
168   It does not check the :const:`Py_TPFLAGS_HAVE_VECTORCALL` flag
169   and it does not fall back to ``tp_call``.
170
171   .. versionadded:: 3.8
172
173
174.. _capi-call:
175
176Object Calling API
177------------------
178
179Various functions are available for calling a Python object.
180Each converts its arguments to a convention supported by the called object –
181either *tp_call* or vectorcall.
182In order to do as little conversion as possible, pick one that best fits
183the format of data you have available.
184
185The following table summarizes the available functions;
186please see individual documentation for details.
187
188+------------------------------------------+------------------+--------------------+---------------+
189| Function                                 | callable         | args               | kwargs        |
190+==========================================+==================+====================+===============+
191| :c:func:`PyObject_Call`                  | ``PyObject *``   | tuple              | dict/``NULL`` |
192+------------------------------------------+------------------+--------------------+---------------+
193| :c:func:`PyObject_CallNoArgs`            | ``PyObject *``   | ---                | ---           |
194+------------------------------------------+------------------+--------------------+---------------+
195| :c:func:`PyObject_CallOneArg`            | ``PyObject *``   | 1 object           | ---           |
196+------------------------------------------+------------------+--------------------+---------------+
197| :c:func:`PyObject_CallObject`            | ``PyObject *``   | tuple/``NULL``     | ---           |
198+------------------------------------------+------------------+--------------------+---------------+
199| :c:func:`PyObject_CallFunction`          | ``PyObject *``   | format             | ---           |
200+------------------------------------------+------------------+--------------------+---------------+
201| :c:func:`PyObject_CallMethod`            | obj + ``char*``  | format             | ---           |
202+------------------------------------------+------------------+--------------------+---------------+
203| :c:func:`PyObject_CallFunctionObjArgs`   | ``PyObject *``   | variadic           | ---           |
204+------------------------------------------+------------------+--------------------+---------------+
205| :c:func:`PyObject_CallMethodObjArgs`     | obj + name       | variadic           | ---           |
206+------------------------------------------+------------------+--------------------+---------------+
207| :c:func:`PyObject_CallMethodNoArgs`      | obj + name       | ---                | ---           |
208+------------------------------------------+------------------+--------------------+---------------+
209| :c:func:`PyObject_CallMethodOneArg`      | obj + name       | 1 object           | ---           |
210+------------------------------------------+------------------+--------------------+---------------+
211| :c:func:`PyObject_Vectorcall`            | ``PyObject *``   | vectorcall         | vectorcall    |
212+------------------------------------------+------------------+--------------------+---------------+
213| :c:func:`PyObject_VectorcallDict`        | ``PyObject *``   | vectorcall         | dict/``NULL`` |
214+------------------------------------------+------------------+--------------------+---------------+
215| :c:func:`PyObject_VectorcallMethod`      | arg + name       | vectorcall         | vectorcall    |
216+------------------------------------------+------------------+--------------------+---------------+
217
218
219.. c:function:: PyObject* PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
220
221   Call a callable Python object *callable*, with arguments given by the
222   tuple *args*, and named arguments given by the dictionary *kwargs*.
223
224   *args* must not be *NULL*; use an empty tuple if no arguments are needed.
225   If no named arguments are needed, *kwargs* can be *NULL*.
226
227   Return the result of the call on success, or raise an exception and return
228   *NULL* on failure.
229
230   This is the equivalent of the Python expression:
231   ``callable(*args, **kwargs)``.
232
233
234.. c:function:: PyObject* PyObject_CallNoArgs(PyObject *callable)
235
236   Call a callable Python object *callable* without any arguments. It is the
237   most efficient way to call a callable Python object without any argument.
238
239   Return the result of the call on success, or raise an exception and return
240   *NULL* on failure.
241
242   .. versionadded:: 3.9
243
244
245.. c:function:: PyObject* PyObject_CallOneArg(PyObject *callable, PyObject *arg)
246
247   Call a callable Python object *callable* with exactly 1 positional argument
248   *arg* and no keyword arguments.
249
250   Return the result of the call on success, or raise an exception and return
251   *NULL* on failure.
252
253   .. versionadded:: 3.9
254
255
256.. c:function:: PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)
257
258   Call a callable Python object *callable*, with arguments given by the
259   tuple *args*.  If no arguments are needed, then *args* can be *NULL*.
260
261   Return the result of the call on success, or raise an exception and return
262   *NULL* on failure.
263
264   This is the equivalent of the Python expression: ``callable(*args)``.
265
266
267.. c:function:: PyObject* PyObject_CallFunction(PyObject *callable, const char *format, ...)
268
269   Call a callable Python object *callable*, with a variable number of C arguments.
270   The C arguments are described using a :c:func:`Py_BuildValue` style format
271   string.  The format can be *NULL*, indicating that no arguments are provided.
272
273   Return the result of the call on success, or raise an exception and return
274   *NULL* on failure.
275
276   This is the equivalent of the Python expression: ``callable(*args)``.
277
278   Note that if you only pass :c:expr:`PyObject *` args,
279   :c:func:`PyObject_CallFunctionObjArgs` is a faster alternative.
280
281   .. versionchanged:: 3.4
282      The type of *format* was changed from ``char *``.
283
284
285.. c:function:: PyObject* PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
286
287   Call the method named *name* of object *obj* with a variable number of C
288   arguments.  The C arguments are described by a :c:func:`Py_BuildValue` format
289   string that should produce a tuple.
290
291   The format can be *NULL*, indicating that no arguments are provided.
292
293   Return the result of the call on success, or raise an exception and return
294   *NULL* on failure.
295
296   This is the equivalent of the Python expression:
297   ``obj.name(arg1, arg2, ...)``.
298
299   Note that if you only pass :c:expr:`PyObject *` args,
300   :c:func:`PyObject_CallMethodObjArgs` is a faster alternative.
301
302   .. versionchanged:: 3.4
303      The types of *name* and *format* were changed from ``char *``.
304
305
306.. c:function:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ...)
307
308   Call a callable Python object *callable*, with a variable number of
309   :c:expr:`PyObject *` arguments.  The arguments are provided as a variable number
310   of parameters followed by *NULL*.
311
312   Return the result of the call on success, or raise an exception and return
313   *NULL* on failure.
314
315   This is the equivalent of the Python expression:
316   ``callable(arg1, arg2, ...)``.
317
318
319.. c:function:: PyObject* PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ...)
320
321   Call a method of the Python object *obj*, where the name of the method is given as a
322   Python string object in *name*.  It is called with a variable number of
323   :c:expr:`PyObject *` arguments.  The arguments are provided as a variable number
324   of parameters followed by *NULL*.
325
326   Return the result of the call on success, or raise an exception and return
327   *NULL* on failure.
328
329
330.. c:function:: PyObject* PyObject_CallMethodNoArgs(PyObject *obj, PyObject *name)
331
332   Call a method of the Python object *obj* without arguments,
333   where the name of the method is given as a Python string object in *name*.
334
335   Return the result of the call on success, or raise an exception and return
336   *NULL* on failure.
337
338   .. versionadded:: 3.9
339
340
341.. c:function:: PyObject* PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
342
343   Call a method of the Python object *obj* with a single positional argument
344   *arg*, where the name of the method is given as a Python string object in
345   *name*.
346
347   Return the result of the call on success, or raise an exception and return
348   *NULL* on failure.
349
350   .. versionadded:: 3.9
351
352
353.. c:function:: PyObject* PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)
354
355   Call a callable Python object *callable*.
356   The arguments are the same as for :c:type:`vectorcallfunc`.
357   If *callable* supports vectorcall_, this directly calls
358   the vectorcall function stored in *callable*.
359
360   Return the result of the call on success, or raise an exception and return
361   *NULL* on failure.
362
363   .. versionadded:: 3.9
364
365.. c:function:: PyObject* PyObject_VectorcallDict(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwdict)
366
367   Call *callable* with positional arguments passed exactly as in the vectorcall_ protocol,
368   but with keyword arguments passed as a dictionary *kwdict*.
369   The *args* array contains only the positional arguments.
370
371   Regardless of which protocol is used internally,
372   a conversion of arguments needs to be done.
373   Therefore, this function should only be used if the caller
374   already has a dictionary ready to use for the keyword arguments,
375   but not a tuple for the positional arguments.
376
377   .. versionadded:: 3.9
378
379.. c:function:: PyObject* PyObject_VectorcallMethod(PyObject *name, PyObject *const *args, size_t nargsf, PyObject *kwnames)
380
381   Call a method using the vectorcall calling convention. The name of the method
382   is given as a Python string *name*. The object whose method is called is
383   *args[0]*, and the *args* array starting at *args[1]* represents the arguments
384   of the call. There must be at least one positional argument.
385   *nargsf* is the number of positional arguments including *args[0]*,
386   plus :const:`PY_VECTORCALL_ARGUMENTS_OFFSET` if the value of ``args[0]`` may
387   temporarily be changed. Keyword arguments can be passed just like in
388   :c:func:`PyObject_Vectorcall`.
389
390   If the object has the :const:`Py_TPFLAGS_METHOD_DESCRIPTOR` feature,
391   this will call the unbound method object with the full
392   *args* vector as arguments.
393
394   Return the result of the call on success, or raise an exception and return
395   *NULL* on failure.
396
397   .. versionadded:: 3.9
398
399
400Call Support API
401----------------
402
403.. c:function:: int PyCallable_Check(PyObject *o)
404
405   Determine if the object *o* is callable.  Return ``1`` if the object is callable
406   and ``0`` otherwise.  This function always succeeds.
407