• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _object:
4
5Object Protocol
6===============
7
8
9.. c:var:: PyObject* Py_NotImplemented
10
11   The ``NotImplemented`` singleton, used to signal that an operation is
12   not implemented for the given type combination.
13
14
15.. c:macro:: Py_RETURN_NOTIMPLEMENTED
16
17   Properly handle returning :c:data:`Py_NotImplemented` from within a C
18   function (that is, increment the reference count of NotImplemented and
19   return it).
20
21
22.. c:function:: int PyObject_Print(PyObject *o, FILE *fp, int flags)
23
24   Print an object *o*, on file *fp*.  Returns ``-1`` on error.  The flags argument
25   is used to enable certain printing options.  The only option currently supported
26   is :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
27   instead of the :func:`repr`.
28
29
30.. c:function:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name)
31
32   Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise.  This
33   is equivalent to the Python expression ``hasattr(o, attr_name)``.  This function
34   always succeeds.
35
36   Note that exceptions which occur while calling :meth:`__getattr__` and
37   :meth:`__getattribute__` methods will get suppressed.
38   To get error reporting use :c:func:`PyObject_GetAttr()` instead.
39
40
41.. c:function:: int PyObject_HasAttrString(PyObject *o, const char *attr_name)
42
43   Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise.  This
44   is equivalent to the Python expression ``hasattr(o, attr_name)``.  This function
45   always succeeds.
46
47   Note that exceptions which occur while calling :meth:`__getattr__` and
48   :meth:`__getattribute__` methods and creating a temporary string object
49   will get suppressed.
50   To get error reporting use :c:func:`PyObject_GetAttrString()` instead.
51
52
53.. c:function:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name)
54
55   Retrieve an attribute named *attr_name* from object *o*. Returns the attribute
56   value on success, or ``NULL`` on failure.  This is the equivalent of the Python
57   expression ``o.attr_name``.
58
59
60.. c:function:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name)
61
62   Retrieve an attribute named *attr_name* from object *o*. Returns the attribute
63   value on success, or ``NULL`` on failure. This is the equivalent of the Python
64   expression ``o.attr_name``.
65
66
67.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name)
68
69   Generic attribute getter function that is meant to be put into a type
70   object's ``tp_getattro`` slot.  It looks for a descriptor in the dictionary
71   of classes in the object's MRO as well as an attribute in the object's
72   :attr:`~object.__dict__` (if present).  As outlined in :ref:`descriptors`,
73   data descriptors take preference over instance attributes, while non-data
74   descriptors don't.  Otherwise, an :exc:`AttributeError` is raised.
75
76
77.. c:function:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)
78
79   Set the value of the attribute named *attr_name*, for object *o*, to the value
80   *v*. Raise an exception and return ``-1`` on failure;
81   return ``0`` on success.  This is the equivalent of the Python statement
82   ``o.attr_name = v``.
83
84   If *v* is ``NULL``, the attribute is deleted, however this feature is
85   deprecated in favour of using :c:func:`PyObject_DelAttr`.
86
87
88.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
89
90   Set the value of the attribute named *attr_name*, for object *o*, to the value
91   *v*. Raise an exception and return ``-1`` on failure;
92   return ``0`` on success.  This is the equivalent of the Python statement
93   ``o.attr_name = v``.
94
95   If *v* is ``NULL``, the attribute is deleted, however this feature is
96   deprecated in favour of using :c:func:`PyObject_DelAttrString`.
97
98
99.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
100
101   Generic attribute setter and deleter function that is meant
102   to be put into a type object's :c:member:`~PyTypeObject.tp_setattro`
103   slot.  It looks for a data descriptor in the
104   dictionary of classes in the object's MRO, and if found it takes preference
105   over setting or deleting the attribute in the instance dictionary. Otherwise, the
106   attribute is set or deleted in the object's :attr:`~object.__dict__` (if present).
107   On success, ``0`` is returned, otherwise an :exc:`AttributeError`
108   is raised and ``-1`` is returned.
109
110
111.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
112
113   Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure.
114   This is the equivalent of the Python statement ``del o.attr_name``.
115
116
117.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name)
118
119   Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure.
120   This is the equivalent of the Python statement ``del o.attr_name``.
121
122
123.. c:function:: PyObject* PyObject_GenericGetDict(PyObject *o, void *context)
124
125   A generic implementation for the getter of a ``__dict__`` descriptor. It
126   creates the dictionary if necessary.
127
128   .. versionadded:: 3.3
129
130
131.. c:function:: int PyObject_GenericSetDict(PyObject *o, void *context)
132
133   A generic implementation for the setter of a ``__dict__`` descriptor. This
134   implementation does not allow the dictionary to be deleted.
135
136   .. versionadded:: 3.3
137
138
139.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
140
141   Compare the values of *o1* and *o2* using the operation specified by *opid*,
142   which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`,
143   :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``,
144   ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. This is the equivalent of
145   the Python expression ``o1 op o2``, where ``op`` is the operator corresponding
146   to *opid*. Returns the value of the comparison on success, or ``NULL`` on failure.
147
148
149.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
150
151   Compare the values of *o1* and *o2* using the operation specified by *opid*,
152   which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`,
153   :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``,
154   ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. Returns ``-1`` on error,
155   ``0`` if the result is false, ``1`` otherwise. This is the equivalent of the
156   Python expression ``o1 op o2``, where ``op`` is the operator corresponding to
157   *opid*.
158
159.. note::
160   If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool`
161   will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`.
162
163.. c:function:: PyObject* PyObject_Repr(PyObject *o)
164
165   .. index:: builtin: repr
166
167   Compute a string representation of object *o*.  Returns the string
168   representation on success, ``NULL`` on failure.  This is the equivalent of the
169   Python expression ``repr(o)``.  Called by the :func:`repr` built-in function.
170
171   .. versionchanged:: 3.4
172      This function now includes a debug assertion to help ensure that it
173      does not silently discard an active exception.
174
175.. c:function:: PyObject* PyObject_ASCII(PyObject *o)
176
177   .. index:: builtin: ascii
178
179   As :c:func:`PyObject_Repr`, compute a string representation of object *o*, but
180   escape the non-ASCII characters in the string returned by
181   :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes.  This generates
182   a string similar to that returned by :c:func:`PyObject_Repr` in Python 2.
183   Called by the :func:`ascii` built-in function.
184
185   .. index:: string; PyObject_Str (C function)
186
187
188.. c:function:: PyObject* PyObject_Str(PyObject *o)
189
190   Compute a string representation of object *o*.  Returns the string
191   representation on success, ``NULL`` on failure.  This is the equivalent of the
192   Python expression ``str(o)``.  Called by the :func:`str` built-in function
193   and, therefore, by the :func:`print` function.
194
195   .. versionchanged:: 3.4
196      This function now includes a debug assertion to help ensure that it
197      does not silently discard an active exception.
198
199.. c:function:: PyObject* PyObject_Bytes(PyObject *o)
200
201   .. index:: builtin: bytes
202
203   Compute a bytes representation of object *o*.  ``NULL`` is returned on
204   failure and a bytes object on success.  This is equivalent to the Python
205   expression ``bytes(o)``, when *o* is not an integer.  Unlike ``bytes(o)``,
206   a TypeError is raised when *o* is an integer instead of a zero-initialized
207   bytes object.
208
209
210.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
211
212   Return ``1`` if the class *derived* is identical to or derived from the class
213   *cls*, otherwise return ``0``.  In case of an error, return ``-1``.
214
215   If *cls* is a tuple, the check will be done against every entry in *cls*.
216   The result will be ``1`` when at least one of the checks returns ``1``,
217   otherwise it will be ``0``.
218
219   If *cls* has a :meth:`~class.__subclasscheck__` method, it will be called to
220   determine the subclass status as described in :pep:`3119`.  Otherwise,
221   *derived* is a subclass of *cls* if it is a direct or indirect subclass,
222   i.e. contained in ``cls.__mro__``.
223
224   Normally only class objects, i.e. instances of :class:`type` or a derived
225   class, are considered classes.  However, objects can override this by having
226   a :attr:`__bases__` attribute (which must be a tuple of base classes).
227
228
229.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls)
230
231   Return ``1`` if *inst* is an instance of the class *cls* or a subclass of
232   *cls*, or ``0`` if not.  On error, returns ``-1`` and sets an exception.
233
234   If *cls* is a tuple, the check will be done against every entry in *cls*.
235   The result will be ``1`` when at least one of the checks returns ``1``,
236   otherwise it will be ``0``.
237
238   If *cls* has a :meth:`~class.__instancecheck__` method, it will be called to
239   determine the subclass status as described in :pep:`3119`.  Otherwise, *inst*
240   is an instance of *cls* if its class is a subclass of *cls*.
241
242   An instance *inst* can override what is considered its class by having a
243   :attr:`__class__` attribute.
244
245   An object *cls* can override if it is considered a class, and what its base
246   classes are, by having a :attr:`__bases__` attribute (which must be a tuple
247   of base classes).
248
249
250.. c:function:: int PyCallable_Check(PyObject *o)
251
252   Determine if the object *o* is callable.  Return ``1`` if the object is callable
253   and ``0`` otherwise.  This function always succeeds.
254
255
256.. c:function:: PyObject* PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)
257
258   Call a callable Python object *callable*, with arguments given by the
259   tuple *args*, and named arguments given by the dictionary *kwargs*.
260
261   *args* must not be ``NULL``, use an empty tuple if no arguments are needed.
262   If no named arguments are needed, *kwargs* can be ``NULL``.
263
264   Return the result of the call on success, or raise an exception and return
265   ``NULL`` on failure.
266
267   This is the equivalent of the Python expression:
268   ``callable(*args, **kwargs)``.
269
270
271.. c:function:: PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)
272
273   Call a callable Python object *callable*, with arguments given by the
274   tuple *args*.  If no arguments are needed, then *args* can be ``NULL``.
275
276   Return the result of the call on success, or raise an exception and return
277   ``NULL`` on failure.
278
279   This is the equivalent of the Python expression: ``callable(*args)``.
280
281
282.. c:function:: PyObject* PyObject_CallFunction(PyObject *callable, const char *format, ...)
283
284   Call a callable Python object *callable*, with a variable number of C arguments.
285   The C arguments are described using a :c:func:`Py_BuildValue` style format
286   string.  The format can be ``NULL``, indicating that no arguments are provided.
287
288   Return the result of the call on success, or raise an exception and return
289   ``NULL`` on failure.
290
291   This is the equivalent of the Python expression: ``callable(*args)``.
292
293   Note that if you only pass :c:type:`PyObject \*` args,
294   :c:func:`PyObject_CallFunctionObjArgs` is a faster alternative.
295
296   .. versionchanged:: 3.4
297      The type of *format* was changed from ``char *``.
298
299
300.. c:function:: PyObject* PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)
301
302   Call the method named *name* of object *obj* with a variable number of C
303   arguments.  The C arguments are described by a :c:func:`Py_BuildValue` format
304   string that should  produce a tuple.
305
306   The format can be ``NULL``, indicating that no arguments are provided.
307
308   Return the result of the call on success, or raise an exception and return
309   ``NULL`` on failure.
310
311   This is the equivalent of the Python expression:
312   ``obj.name(arg1, arg2, ...)``.
313
314   Note that if you only pass :c:type:`PyObject \*` args,
315   :c:func:`PyObject_CallMethodObjArgs` is a faster alternative.
316
317   .. versionchanged:: 3.4
318      The types of *name* and *format* were changed from ``char *``.
319
320
321.. c:function:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)
322
323   Call a callable Python object *callable*, with a variable number of
324   :c:type:`PyObject\*` arguments.  The arguments are provided as a variable number
325   of parameters followed by ``NULL``.
326
327   Return the result of the call on success, or raise an exception and return
328   ``NULL`` on failure.
329
330   This is the equivalent of the Python expression:
331   ``callable(arg1, arg2, ...)``.
332
333
334.. c:function:: PyObject* PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ..., NULL)
335
336   Calls a method of the Python object *obj*, where the name of the method is given as a
337   Python string object in *name*.  It is called with a variable number of
338   :c:type:`PyObject\*` arguments.  The arguments are provided as a variable number
339   of parameters followed by ``NULL``.
340
341   Return the result of the call on success, or raise an exception and return
342   ``NULL`` on failure.
343
344
345.. c:function:: PyObject* _PyObject_Vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)
346
347   Call a callable Python object *callable*, using
348   :c:data:`vectorcall <PyTypeObject.tp_vectorcall_offset>` if possible.
349
350   *args* is a C array with the positional arguments.
351
352   *nargsf* is the number of positional arguments plus optionally the flag
353   :const:`PY_VECTORCALL_ARGUMENTS_OFFSET` (see below).
354   To get actual number of arguments, use
355   :c:func:`PyVectorcall_NARGS(nargsf) <PyVectorcall_NARGS>`.
356
357   *kwnames* can be either ``NULL`` (no keyword arguments) or a tuple of keyword
358   names. In the latter case, the values of the keyword arguments are stored
359   in *args* after the positional arguments.
360   The number of keyword arguments does not influence *nargsf*.
361
362   *kwnames* must contain only objects of type ``str`` (not a subclass),
363   and all keys must be unique.
364
365   Return the result of the call on success, or raise an exception and return
366   ``NULL`` on failure.
367
368   This uses the vectorcall protocol if the callable supports it;
369   otherwise, the arguments are converted to use
370   :c:member:`~PyTypeObject.tp_call`.
371
372   .. note::
373
374      This function is provisional and expected to become public in Python 3.9,
375      with a different name and, possibly, changed semantics.
376      If you use the function, plan for updating your code for Python 3.9.
377
378   .. versionadded:: 3.8
379
380.. c:var:: PY_VECTORCALL_ARGUMENTS_OFFSET
381
382   If set in a vectorcall *nargsf* argument, the callee is allowed to
383   temporarily change ``args[-1]``. In other words, *args* points to
384   argument 1 (not 0) in the allocated vector.
385   The callee must restore the value of ``args[-1]`` before returning.
386
387   Whenever they can do so cheaply (without additional allocation), callers
388   are encouraged to use :const:`PY_VECTORCALL_ARGUMENTS_OFFSET`.
389   Doing so will allow callables such as bound methods to make their onward
390   calls (which include a prepended *self* argument) cheaply.
391
392   .. versionadded:: 3.8
393
394.. c:function:: Py_ssize_t PyVectorcall_NARGS(size_t nargsf)
395
396   Given a vectorcall *nargsf* argument, return the actual number of
397   arguments.
398   Currently equivalent to ``nargsf & ~PY_VECTORCALL_ARGUMENTS_OFFSET``.
399
400   .. versionadded:: 3.8
401
402.. c:function:: PyObject* _PyObject_FastCallDict(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwdict)
403
404   Same as :c:func:`_PyObject_Vectorcall` except that the keyword arguments
405   are passed as a dictionary in *kwdict*. This may be ``NULL`` if there
406   are no keyword arguments.
407
408   For callables supporting :c:data:`vectorcall <PyTypeObject.tp_vectorcall_offset>`,
409   the arguments are internally converted to the vectorcall convention.
410   Therefore, this function adds some overhead compared to
411   :c:func:`_PyObject_Vectorcall`.
412   It should only be used if the caller already has a dictionary ready to use.
413
414   .. note::
415
416      This function is provisional and expected to become public in Python 3.9,
417      with a different name and, possibly, changed semantics.
418      If you use the function, plan for updating your code for Python 3.9.
419
420   .. versionadded:: 3.8
421
422
423.. c:function:: Py_hash_t PyObject_Hash(PyObject *o)
424
425   .. index:: builtin: hash
426
427   Compute and return the hash value of an object *o*.  On failure, return ``-1``.
428   This is the equivalent of the Python expression ``hash(o)``.
429
430   .. versionchanged:: 3.2
431      The return type is now Py_hash_t.  This is a signed integer the same size
432      as Py_ssize_t.
433
434
435.. c:function:: Py_hash_t PyObject_HashNotImplemented(PyObject *o)
436
437   Set a :exc:`TypeError` indicating that ``type(o)`` is not hashable and return ``-1``.
438   This function receives special treatment when stored in a ``tp_hash`` slot,
439   allowing a type to explicitly indicate to the interpreter that it is not
440   hashable.
441
442
443.. c:function:: int PyObject_IsTrue(PyObject *o)
444
445   Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise.
446   This is equivalent to the Python expression ``not not o``.  On failure, return
447   ``-1``.
448
449
450.. c:function:: int PyObject_Not(PyObject *o)
451
452   Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise.
453   This is equivalent to the Python expression ``not o``.  On failure, return
454   ``-1``.
455
456
457.. c:function:: PyObject* PyObject_Type(PyObject *o)
458
459   .. index:: builtin: type
460
461   When *o* is non-``NULL``, returns a type object corresponding to the object type
462   of object *o*. On failure, raises :exc:`SystemError` and returns ``NULL``.  This
463   is equivalent to the Python expression ``type(o)``. This function increments the
464   reference count of the return value. There's really no reason to use this
465   function instead of the common expression ``o->ob_type``, which returns a
466   pointer of type :c:type:`PyTypeObject\*`, except when the incremented reference
467   count is needed.
468
469
470.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)
471
472   Return true if the object *o* is of type *type* or a subtype of *type*.  Both
473   parameters must be non-``NULL``.
474
475
476.. c:function:: Py_ssize_t PyObject_Size(PyObject *o)
477               Py_ssize_t PyObject_Length(PyObject *o)
478
479   .. index:: builtin: len
480
481   Return the length of object *o*.  If the object *o* provides either the sequence
482   and mapping protocols, the sequence length is returned.  On error, ``-1`` is
483   returned.  This is the equivalent to the Python expression ``len(o)``.
484
485
486.. c:function:: Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t default)
487
488   Return an estimated length for the object *o*. First try to return its
489   actual length, then an estimate using :meth:`~object.__length_hint__`, and
490   finally return the default value. On error return ``-1``. This is the
491   equivalent to the Python expression ``operator.length_hint(o, default)``.
492
493   .. versionadded:: 3.4
494
495
496.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key)
497
498   Return element of *o* corresponding to the object *key* or ``NULL`` on failure.
499   This is the equivalent of the Python expression ``o[key]``.
500
501
502.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)
503
504   Map the object *key* to the value *v*.  Raise an exception and
505   return ``-1`` on failure; return ``0`` on success.  This is the
506   equivalent of the Python statement ``o[key] = v``.
507
508
509.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key)
510
511   Remove the mapping for the object *key* from the object *o*.  Return ``-1``
512   on failure.  This is equivalent to the Python statement ``del o[key]``.
513
514
515.. c:function:: PyObject* PyObject_Dir(PyObject *o)
516
517   This is equivalent to the Python expression ``dir(o)``, returning a (possibly
518   empty) list of strings appropriate for the object argument, or ``NULL`` if there
519   was an error.  If the argument is ``NULL``, this is like the Python ``dir()``,
520   returning the names of the current locals; in this case, if no execution frame
521   is active then ``NULL`` is returned but :c:func:`PyErr_Occurred` will return false.
522
523
524.. c:function:: PyObject* PyObject_GetIter(PyObject *o)
525
526   This is equivalent to the Python expression ``iter(o)``. It returns a new
527   iterator for the object argument, or the object  itself if the object is already
528   an iterator.  Raises :exc:`TypeError` and returns ``NULL`` if the object cannot be
529   iterated.
530