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. This behaviour is deprecated
85   in favour of using :c:func:`PyObject_DelAttr`, but there are currently no
86   plans to remove it.
87
88
89.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)
90
91   Set the value of the attribute named *attr_name*, for object *o*, to the value
92   *v*. Raise an exception and return ``-1`` on failure;
93   return ``0`` on success.  This is the equivalent of the Python statement
94   ``o.attr_name = v``.
95
96   If *v* is ``NULL``, the attribute is deleted, but this feature is
97   deprecated in favour of using :c:func:`PyObject_DelAttrString`.
98
99
100.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)
101
102   Generic attribute setter and deleter function that is meant
103   to be put into a type object's :c:member:`~PyTypeObject.tp_setattro`
104   slot.  It looks for a data descriptor in the
105   dictionary of classes in the object's MRO, and if found it takes preference
106   over setting or deleting the attribute in the instance dictionary. Otherwise, the
107   attribute is set or deleted in the object's :attr:`~object.__dict__` (if present).
108   On success, ``0`` is returned, otherwise an :exc:`AttributeError`
109   is raised and ``-1`` is returned.
110
111
112.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name)
113
114   Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure.
115   This is the equivalent of the Python statement ``del o.attr_name``.
116
117
118.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name)
119
120   Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure.
121   This is the equivalent of the Python statement ``del o.attr_name``.
122
123
124.. c:function:: PyObject* PyObject_GenericGetDict(PyObject *o, void *context)
125
126   A generic implementation for the getter of a ``__dict__`` descriptor. It
127   creates the dictionary if necessary.
128
129   This function may also be called to get the :py:attr:`~object.__dict__`
130   of the object *o*. Pass ``NULL`` for *context* when calling it.
131   Since this function may need to allocate memory for the
132   dictionary, it may be more efficient to call :c:func:`PyObject_GetAttr`
133   when accessing an attribute on the object.
134
135   On failure, returns ``NULL`` with an exception set.
136
137   .. versionadded:: 3.3
138
139
140.. c:function:: int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)
141
142   A generic implementation for the setter of a ``__dict__`` descriptor. This
143   implementation does not allow the dictionary to be deleted.
144
145   .. versionadded:: 3.3
146
147
148.. c:function:: PyObject** _PyObject_GetDictPtr(PyObject *obj)
149
150   Return a pointer to :py:attr:`~object.__dict__` of the object *obj*.
151   If there is no ``__dict__``, return ``NULL`` without setting an exception.
152
153   This function may need to allocate memory for the
154   dictionary, so it may be more efficient to call :c:func:`PyObject_GetAttr`
155   when accessing an attribute on the object.
156
157
158.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
159
160   Compare the values of *o1* and *o2* using the operation specified by *opid*,
161   which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`,
162   :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``,
163   ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. This is the equivalent of
164   the Python expression ``o1 op o2``, where ``op`` is the operator corresponding
165   to *opid*. Returns the value of the comparison on success, or ``NULL`` on failure.
166
167
168.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)
169
170   Compare the values of *o1* and *o2* using the operation specified by *opid*,
171   which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`,
172   :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``,
173   ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. Returns ``-1`` on error,
174   ``0`` if the result is false, ``1`` otherwise. This is the equivalent of the
175   Python expression ``o1 op o2``, where ``op`` is the operator corresponding to
176   *opid*.
177
178.. note::
179   If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool`
180   will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`.
181
182.. c:function:: PyObject* PyObject_Format(PyObject *obj, PyObject *format_spec)
183
184   Format *obj* using *format_spec*. This is equivalent to the Python
185   expression ``format(obj, format_spec)``.
186
187   *format_spec* may be ``NULL``. In this case the call is equivalent
188   to ``format(obj)``.
189   Returns the formatted string on success, ``NULL`` on failure.
190
191.. c:function:: PyObject* PyObject_Repr(PyObject *o)
192
193   .. index:: pair: built-in function; repr
194
195   Compute a string representation of object *o*.  Returns the string
196   representation on success, ``NULL`` on failure.  This is the equivalent of the
197   Python expression ``repr(o)``.  Called by the :func:`repr` built-in function.
198
199   .. versionchanged:: 3.4
200      This function now includes a debug assertion to help ensure that it
201      does not silently discard an active exception.
202
203.. c:function:: PyObject* PyObject_ASCII(PyObject *o)
204
205   .. index:: pair: built-in function; ascii
206
207   As :c:func:`PyObject_Repr`, compute a string representation of object *o*, but
208   escape the non-ASCII characters in the string returned by
209   :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes.  This generates
210   a string similar to that returned by :c:func:`PyObject_Repr` in Python 2.
211   Called by the :func:`ascii` built-in function.
212
213   .. index:: string; PyObject_Str (C function)
214
215
216.. c:function:: PyObject* PyObject_Str(PyObject *o)
217
218   Compute a string representation of object *o*.  Returns the string
219   representation on success, ``NULL`` on failure.  This is the equivalent of the
220   Python expression ``str(o)``.  Called by the :func:`str` built-in function
221   and, therefore, by the :func:`print` function.
222
223   .. versionchanged:: 3.4
224      This function now includes a debug assertion to help ensure that it
225      does not silently discard an active exception.
226
227
228.. c:function:: PyObject* PyObject_Bytes(PyObject *o)
229
230   .. index:: pair: built-in function; bytes
231
232   Compute a bytes representation of object *o*.  ``NULL`` is returned on
233   failure and a bytes object on success.  This is equivalent to the Python
234   expression ``bytes(o)``, when *o* is not an integer.  Unlike ``bytes(o)``,
235   a TypeError is raised when *o* is an integer instead of a zero-initialized
236   bytes object.
237
238
239.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls)
240
241   Return ``1`` if the class *derived* is identical to or derived from the class
242   *cls*, otherwise return ``0``.  In case of an error, return ``-1``.
243
244   If *cls* is a tuple, the check will be done against every entry in *cls*.
245   The result will be ``1`` when at least one of the checks returns ``1``,
246   otherwise it will be ``0``.
247
248   If *cls* has a :meth:`~class.__subclasscheck__` method, it will be called to
249   determine the subclass status as described in :pep:`3119`.  Otherwise,
250   *derived* is a subclass of *cls* if it is a direct or indirect subclass,
251   i.e. contained in ``cls.__mro__``.
252
253   Normally only class objects, i.e. instances of :class:`type` or a derived
254   class, are considered classes.  However, objects can override this by having
255   a :attr:`__bases__` attribute (which must be a tuple of base classes).
256
257
258.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls)
259
260   Return ``1`` if *inst* is an instance of the class *cls* or a subclass of
261   *cls*, or ``0`` if not.  On error, returns ``-1`` and sets an exception.
262
263   If *cls* is a tuple, the check will be done against every entry in *cls*.
264   The result will be ``1`` when at least one of the checks returns ``1``,
265   otherwise it will be ``0``.
266
267   If *cls* has a :meth:`~class.__instancecheck__` method, it will be called to
268   determine the subclass status as described in :pep:`3119`.  Otherwise, *inst*
269   is an instance of *cls* if its class is a subclass of *cls*.
270
271   An instance *inst* can override what is considered its class by having a
272   :attr:`__class__` attribute.
273
274   An object *cls* can override if it is considered a class, and what its base
275   classes are, by having a :attr:`__bases__` attribute (which must be a tuple
276   of base classes).
277
278
279.. c:function:: Py_hash_t PyObject_Hash(PyObject *o)
280
281   .. index:: pair: built-in function; hash
282
283   Compute and return the hash value of an object *o*.  On failure, return ``-1``.
284   This is the equivalent of the Python expression ``hash(o)``.
285
286   .. versionchanged:: 3.2
287      The return type is now Py_hash_t.  This is a signed integer the same size
288      as :c:type:`Py_ssize_t`.
289
290
291.. c:function:: Py_hash_t PyObject_HashNotImplemented(PyObject *o)
292
293   Set a :exc:`TypeError` indicating that ``type(o)`` is not :term:`hashable` and return ``-1``.
294   This function receives special treatment when stored in a ``tp_hash`` slot,
295   allowing a type to explicitly indicate to the interpreter that it is not
296   hashable.
297
298
299.. c:function:: int PyObject_IsTrue(PyObject *o)
300
301   Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise.
302   This is equivalent to the Python expression ``not not o``.  On failure, return
303   ``-1``.
304
305
306.. c:function:: int PyObject_Not(PyObject *o)
307
308   Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise.
309   This is equivalent to the Python expression ``not o``.  On failure, return
310   ``-1``.
311
312
313.. c:function:: PyObject* PyObject_Type(PyObject *o)
314
315   .. index:: pair: built-in function; type
316
317   When *o* is non-``NULL``, returns a type object corresponding to the object type
318   of object *o*. On failure, raises :exc:`SystemError` and returns ``NULL``.  This
319   is equivalent to the Python expression ``type(o)``. This function increments the
320   reference count of the return value. There's really no reason to use this
321   function instead of the :c:func:`Py_TYPE()` function, which returns a
322   pointer of type :c:expr:`PyTypeObject*`, except when the incremented reference
323   count is needed.
324
325
326.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)
327
328   Return non-zero if the object *o* is of type *type* or a subtype of *type*, and
329   ``0`` otherwise.  Both parameters must be non-``NULL``.
330
331
332.. c:function:: Py_ssize_t PyObject_Size(PyObject *o)
333               Py_ssize_t PyObject_Length(PyObject *o)
334
335   .. index:: pair: built-in function; len
336
337   Return the length of object *o*.  If the object *o* provides either the sequence
338   and mapping protocols, the sequence length is returned.  On error, ``-1`` is
339   returned.  This is the equivalent to the Python expression ``len(o)``.
340
341
342.. c:function:: Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
343
344   Return an estimated length for the object *o*. First try to return its
345   actual length, then an estimate using :meth:`~object.__length_hint__`, and
346   finally return the default value. On error return ``-1``. This is the
347   equivalent to the Python expression ``operator.length_hint(o, defaultvalue)``.
348
349   .. versionadded:: 3.4
350
351
352.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key)
353
354   Return element of *o* corresponding to the object *key* or ``NULL`` on failure.
355   This is the equivalent of the Python expression ``o[key]``.
356
357
358.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)
359
360   Map the object *key* to the value *v*.  Raise an exception and
361   return ``-1`` on failure; return ``0`` on success.  This is the
362   equivalent of the Python statement ``o[key] = v``.  This function *does
363   not* steal a reference to *v*.
364
365
366.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key)
367
368   Remove the mapping for the object *key* from the object *o*.  Return ``-1``
369   on failure.  This is equivalent to the Python statement ``del o[key]``.
370
371
372.. c:function:: PyObject* PyObject_Dir(PyObject *o)
373
374   This is equivalent to the Python expression ``dir(o)``, returning a (possibly
375   empty) list of strings appropriate for the object argument, or ``NULL`` if there
376   was an error.  If the argument is ``NULL``, this is like the Python ``dir()``,
377   returning the names of the current locals; in this case, if no execution frame
378   is active then ``NULL`` is returned but :c:func:`PyErr_Occurred` will return false.
379
380
381.. c:function:: PyObject* PyObject_GetIter(PyObject *o)
382
383   This is equivalent to the Python expression ``iter(o)``. It returns a new
384   iterator for the object argument, or the object  itself if the object is already
385   an iterator.  Raises :exc:`TypeError` and returns ``NULL`` if the object cannot be
386   iterated.
387
388
389.. c:function:: PyObject* PyObject_GetAIter(PyObject *o)
390
391   This is the equivalent to the Python expression ``aiter(o)``. Takes an
392   :class:`AsyncIterable` object and returns an :class:`AsyncIterator` for it.
393   This is typically a new iterator but if the argument is an
394   :class:`AsyncIterator`, this returns itself. Raises :exc:`TypeError` and
395   returns ``NULL`` if the object cannot be iterated.
396
397   .. versionadded:: 3.10
398