1.. highlight:: c 2 3.. _object: 4 5Object Protocol 6=============== 7 8 9.. c:function:: PyObject* Py_GetConstant(unsigned int constant_id) 10 11 Get a :term:`strong reference` to a constant. 12 13 Set an exception and return ``NULL`` if *constant_id* is invalid. 14 15 *constant_id* must be one of these constant identifiers: 16 17 .. c:namespace:: NULL 18 19 ======================================== ===== ========================= 20 Constant Identifier Value Returned object 21 ======================================== ===== ========================= 22 .. c:macro:: Py_CONSTANT_NONE ``0`` :py:data:`None` 23 .. c:macro:: Py_CONSTANT_FALSE ``1`` :py:data:`False` 24 .. c:macro:: Py_CONSTANT_TRUE ``2`` :py:data:`True` 25 .. c:macro:: Py_CONSTANT_ELLIPSIS ``3`` :py:data:`Ellipsis` 26 .. c:macro:: Py_CONSTANT_NOT_IMPLEMENTED ``4`` :py:data:`NotImplemented` 27 .. c:macro:: Py_CONSTANT_ZERO ``5`` ``0`` 28 .. c:macro:: Py_CONSTANT_ONE ``6`` ``1`` 29 .. c:macro:: Py_CONSTANT_EMPTY_STR ``7`` ``''`` 30 .. c:macro:: Py_CONSTANT_EMPTY_BYTES ``8`` ``b''`` 31 .. c:macro:: Py_CONSTANT_EMPTY_TUPLE ``9`` ``()`` 32 ======================================== ===== ========================= 33 34 Numeric values are only given for projects which cannot use the constant 35 identifiers. 36 37 38 .. versionadded:: 3.13 39 40 .. impl-detail:: 41 42 In CPython, all of these constants are :term:`immortal`. 43 44 45.. c:function:: PyObject* Py_GetConstantBorrowed(unsigned int constant_id) 46 47 Similar to :c:func:`Py_GetConstant`, but return a :term:`borrowed 48 reference`. 49 50 This function is primarily intended for backwards compatibility: 51 using :c:func:`Py_GetConstant` is recommended for new code. 52 53 The reference is borrowed from the interpreter, and is valid until the 54 interpreter finalization. 55 56 .. versionadded:: 3.13 57 58 59.. c:var:: PyObject* Py_NotImplemented 60 61 The ``NotImplemented`` singleton, used to signal that an operation is 62 not implemented for the given type combination. 63 64 65.. c:macro:: Py_RETURN_NOTIMPLEMENTED 66 67 Properly handle returning :c:data:`Py_NotImplemented` from within a C 68 function (that is, create a new :term:`strong reference` 69 to :const:`NotImplemented` and return it). 70 71 72.. c:macro:: Py_PRINT_RAW 73 74 Flag to be used with multiple functions that print the object (like 75 :c:func:`PyObject_Print` and :c:func:`PyFile_WriteObject`). 76 If passed, these function would use the :func:`str` of the object 77 instead of the :func:`repr`. 78 79 80.. c:function:: int PyObject_Print(PyObject *o, FILE *fp, int flags) 81 82 Print an object *o*, on file *fp*. Returns ``-1`` on error. The flags argument 83 is used to enable certain printing options. The only option currently supported 84 is :c:macro:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written 85 instead of the :func:`repr`. 86 87 88.. c:function:: int PyObject_HasAttrWithError(PyObject *o, PyObject *attr_name) 89 90 Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. 91 This is equivalent to the Python expression ``hasattr(o, attr_name)``. 92 On failure, return ``-1``. 93 94 .. versionadded:: 3.13 95 96 97.. c:function:: int PyObject_HasAttrStringWithError(PyObject *o, const char *attr_name) 98 99 This is the same as :c:func:`PyObject_HasAttrWithError`, but *attr_name* is 100 specified as a :c:expr:`const char*` UTF-8 encoded bytes string, 101 rather than a :c:expr:`PyObject*`. 102 103 .. versionadded:: 3.13 104 105 106.. c:function:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name) 107 108 Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise. 109 This function always succeeds. 110 111 .. note:: 112 113 Exceptions that occur when this calls :meth:`~object.__getattr__` and 114 :meth:`~object.__getattribute__` methods are silently ignored. 115 For proper error handling, use :c:func:`PyObject_HasAttrWithError`, 116 :c:func:`PyObject_GetOptionalAttr` or :c:func:`PyObject_GetAttr` instead. 117 118 119.. c:function:: int PyObject_HasAttrString(PyObject *o, const char *attr_name) 120 121 This is the same as :c:func:`PyObject_HasAttr`, but *attr_name* is 122 specified as a :c:expr:`const char*` UTF-8 encoded bytes string, 123 rather than a :c:expr:`PyObject*`. 124 125 .. note:: 126 127 Exceptions that occur when this calls :meth:`~object.__getattr__` and 128 :meth:`~object.__getattribute__` methods or while creating the temporary 129 :class:`str` object are silently ignored. 130 For proper error handling, use :c:func:`PyObject_HasAttrStringWithError`, 131 :c:func:`PyObject_GetOptionalAttrString` 132 or :c:func:`PyObject_GetAttrString` instead. 133 134 135.. c:function:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name) 136 137 Retrieve an attribute named *attr_name* from object *o*. Returns the attribute 138 value on success, or ``NULL`` on failure. This is the equivalent of the Python 139 expression ``o.attr_name``. 140 141 If the missing attribute should not be treated as a failure, you can use 142 :c:func:`PyObject_GetOptionalAttr` instead. 143 144 145.. c:function:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name) 146 147 This is the same as :c:func:`PyObject_GetAttr`, but *attr_name* is 148 specified as a :c:expr:`const char*` UTF-8 encoded bytes string, 149 rather than a :c:expr:`PyObject*`. 150 151 If the missing attribute should not be treated as a failure, you can use 152 :c:func:`PyObject_GetOptionalAttrString` instead. 153 154 155.. c:function:: int PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result); 156 157 Variant of :c:func:`PyObject_GetAttr` which doesn't raise 158 :exc:`AttributeError` if the attribute is not found. 159 160 If the attribute is found, return ``1`` and set *\*result* to a new 161 :term:`strong reference` to the attribute. 162 If the attribute is not found, return ``0`` and set *\*result* to ``NULL``; 163 the :exc:`AttributeError` is silenced. 164 If an error other than :exc:`AttributeError` is raised, return ``-1`` and 165 set *\*result* to ``NULL``. 166 167 .. versionadded:: 3.13 168 169 170.. c:function:: int PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result); 171 172 This is the same as :c:func:`PyObject_GetOptionalAttr`, but *attr_name* is 173 specified as a :c:expr:`const char*` UTF-8 encoded bytes string, 174 rather than a :c:expr:`PyObject*`. 175 176 .. versionadded:: 3.13 177 178.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) 179 180 Generic attribute getter function that is meant to be put into a type 181 object's ``tp_getattro`` slot. It looks for a descriptor in the dictionary 182 of classes in the object's MRO as well as an attribute in the object's 183 :attr:`~object.__dict__` (if present). As outlined in :ref:`descriptors`, 184 data descriptors take preference over instance attributes, while non-data 185 descriptors don't. Otherwise, an :exc:`AttributeError` is raised. 186 187 188.. c:function:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v) 189 190 Set the value of the attribute named *attr_name*, for object *o*, to the value 191 *v*. Raise an exception and return ``-1`` on failure; 192 return ``0`` on success. This is the equivalent of the Python statement 193 ``o.attr_name = v``. 194 195 If *v* is ``NULL``, the attribute is deleted. This behaviour is deprecated 196 in favour of using :c:func:`PyObject_DelAttr`, but there are currently no 197 plans to remove it. 198 199 200.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v) 201 202 This is the same as :c:func:`PyObject_SetAttr`, but *attr_name* is 203 specified as a :c:expr:`const char*` UTF-8 encoded bytes string, 204 rather than a :c:expr:`PyObject*`. 205 206 If *v* is ``NULL``, the attribute is deleted, but this feature is 207 deprecated in favour of using :c:func:`PyObject_DelAttrString`. 208 209 The number of different attribute names passed to this function 210 should be kept small, usually by using a statically allocated string 211 as *attr_name*. 212 For attribute names that aren't known at compile time, prefer calling 213 :c:func:`PyUnicode_FromString` and :c:func:`PyObject_SetAttr` directly. 214 For more details, see :c:func:`PyUnicode_InternFromString`, which may be 215 used internally to create a key object. 216 217.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value) 218 219 Generic attribute setter and deleter function that is meant 220 to be put into a type object's :c:member:`~PyTypeObject.tp_setattro` 221 slot. It looks for a data descriptor in the 222 dictionary of classes in the object's MRO, and if found it takes preference 223 over setting or deleting the attribute in the instance dictionary. Otherwise, the 224 attribute is set or deleted in the object's :attr:`~object.__dict__` (if present). 225 On success, ``0`` is returned, otherwise an :exc:`AttributeError` 226 is raised and ``-1`` is returned. 227 228 229.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name) 230 231 Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure. 232 This is the equivalent of the Python statement ``del o.attr_name``. 233 234 235.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name) 236 237 This is the same as :c:func:`PyObject_DelAttr`, but *attr_name* is 238 specified as a :c:expr:`const char*` UTF-8 encoded bytes string, 239 rather than a :c:expr:`PyObject*`. 240 241 The number of different attribute names passed to this function 242 should be kept small, usually by using a statically allocated string 243 as *attr_name*. 244 For attribute names that aren't known at compile time, prefer calling 245 :c:func:`PyUnicode_FromString` and :c:func:`PyObject_DelAttr` directly. 246 For more details, see :c:func:`PyUnicode_InternFromString`, which may be 247 used internally to create a key object for lookup. 248 249 250.. c:function:: PyObject* PyObject_GenericGetDict(PyObject *o, void *context) 251 252 A generic implementation for the getter of a ``__dict__`` descriptor. It 253 creates the dictionary if necessary. 254 255 This function may also be called to get the :py:attr:`~object.__dict__` 256 of the object *o*. Pass ``NULL`` for *context* when calling it. 257 Since this function may need to allocate memory for the 258 dictionary, it may be more efficient to call :c:func:`PyObject_GetAttr` 259 when accessing an attribute on the object. 260 261 On failure, returns ``NULL`` with an exception set. 262 263 .. versionadded:: 3.3 264 265 266.. c:function:: int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context) 267 268 A generic implementation for the setter of a ``__dict__`` descriptor. This 269 implementation does not allow the dictionary to be deleted. 270 271 .. versionadded:: 3.3 272 273 274.. c:function:: PyObject** _PyObject_GetDictPtr(PyObject *obj) 275 276 Return a pointer to :py:attr:`~object.__dict__` of the object *obj*. 277 If there is no ``__dict__``, return ``NULL`` without setting an exception. 278 279 This function may need to allocate memory for the 280 dictionary, so it may be more efficient to call :c:func:`PyObject_GetAttr` 281 when accessing an attribute on the object. 282 283 284.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid) 285 286 Compare the values of *o1* and *o2* using the operation specified by *opid*, 287 which must be one of :c:macro:`Py_LT`, :c:macro:`Py_LE`, :c:macro:`Py_EQ`, 288 :c:macro:`Py_NE`, :c:macro:`Py_GT`, or :c:macro:`Py_GE`, corresponding to ``<``, 289 ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. This is the equivalent of 290 the Python expression ``o1 op o2``, where ``op`` is the operator corresponding 291 to *opid*. Returns the value of the comparison on success, or ``NULL`` on failure. 292 293 294.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid) 295 296 Compare the values of *o1* and *o2* using the operation specified by *opid*, 297 like :c:func:`PyObject_RichCompare`, but returns ``-1`` on error, ``0`` if 298 the result is false, ``1`` otherwise. 299 300.. note:: 301 If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool` 302 will always return ``1`` for :c:macro:`Py_EQ` and ``0`` for :c:macro:`Py_NE`. 303 304.. c:function:: PyObject* PyObject_Format(PyObject *obj, PyObject *format_spec) 305 306 Format *obj* using *format_spec*. This is equivalent to the Python 307 expression ``format(obj, format_spec)``. 308 309 *format_spec* may be ``NULL``. In this case the call is equivalent 310 to ``format(obj)``. 311 Returns the formatted string on success, ``NULL`` on failure. 312 313.. c:function:: PyObject* PyObject_Repr(PyObject *o) 314 315 .. index:: pair: built-in function; repr 316 317 Compute a string representation of object *o*. Returns the string 318 representation on success, ``NULL`` on failure. This is the equivalent of the 319 Python expression ``repr(o)``. Called by the :func:`repr` built-in function. 320 321 .. versionchanged:: 3.4 322 This function now includes a debug assertion to help ensure that it 323 does not silently discard an active exception. 324 325.. c:function:: PyObject* PyObject_ASCII(PyObject *o) 326 327 .. index:: pair: built-in function; ascii 328 329 As :c:func:`PyObject_Repr`, compute a string representation of object *o*, but 330 escape the non-ASCII characters in the string returned by 331 :c:func:`PyObject_Repr` with ``\x``, ``\u`` or ``\U`` escapes. This generates 332 a string similar to that returned by :c:func:`PyObject_Repr` in Python 2. 333 Called by the :func:`ascii` built-in function. 334 335 .. index:: string; PyObject_Str (C function) 336 337 338.. c:function:: PyObject* PyObject_Str(PyObject *o) 339 340 Compute a string representation of object *o*. Returns the string 341 representation on success, ``NULL`` on failure. This is the equivalent of the 342 Python expression ``str(o)``. Called by the :func:`str` built-in function 343 and, therefore, by the :func:`print` function. 344 345 .. versionchanged:: 3.4 346 This function now includes a debug assertion to help ensure that it 347 does not silently discard an active exception. 348 349 350.. c:function:: PyObject* PyObject_Bytes(PyObject *o) 351 352 .. index:: pair: built-in function; bytes 353 354 Compute a bytes representation of object *o*. ``NULL`` is returned on 355 failure and a bytes object on success. This is equivalent to the Python 356 expression ``bytes(o)``, when *o* is not an integer. Unlike ``bytes(o)``, 357 a TypeError is raised when *o* is an integer instead of a zero-initialized 358 bytes object. 359 360 361.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls) 362 363 Return ``1`` if the class *derived* is identical to or derived from the class 364 *cls*, otherwise return ``0``. In case of an error, return ``-1``. 365 366 If *cls* is a tuple, the check will be done against every entry in *cls*. 367 The result will be ``1`` when at least one of the checks returns ``1``, 368 otherwise it will be ``0``. 369 370 If *cls* has a :meth:`~type.__subclasscheck__` method, it will be called to 371 determine the subclass status as described in :pep:`3119`. Otherwise, 372 *derived* is a subclass of *cls* if it is a direct or indirect subclass, 373 i.e. contained in :attr:`cls.__mro__ <type.__mro__>`. 374 375 Normally only class objects, i.e. instances of :class:`type` or a derived 376 class, are considered classes. However, objects can override this by having 377 a :attr:`~type.__bases__` attribute (which must be a tuple of base classes). 378 379 380.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls) 381 382 Return ``1`` if *inst* is an instance of the class *cls* or a subclass of 383 *cls*, or ``0`` if not. On error, returns ``-1`` and sets an exception. 384 385 If *cls* is a tuple, the check will be done against every entry in *cls*. 386 The result will be ``1`` when at least one of the checks returns ``1``, 387 otherwise it will be ``0``. 388 389 If *cls* has a :meth:`~type.__instancecheck__` method, it will be called to 390 determine the subclass status as described in :pep:`3119`. Otherwise, *inst* 391 is an instance of *cls* if its class is a subclass of *cls*. 392 393 An instance *inst* can override what is considered its class by having a 394 :attr:`~object.__class__` attribute. 395 396 An object *cls* can override if it is considered a class, and what its base 397 classes are, by having a :attr:`~type.__bases__` attribute (which must be a tuple 398 of base classes). 399 400 401.. c:function:: Py_hash_t PyObject_Hash(PyObject *o) 402 403 .. index:: pair: built-in function; hash 404 405 Compute and return the hash value of an object *o*. On failure, return ``-1``. 406 This is the equivalent of the Python expression ``hash(o)``. 407 408 .. versionchanged:: 3.2 409 The return type is now Py_hash_t. This is a signed integer the same size 410 as :c:type:`Py_ssize_t`. 411 412 413.. c:function:: Py_hash_t PyObject_HashNotImplemented(PyObject *o) 414 415 Set a :exc:`TypeError` indicating that ``type(o)`` is not :term:`hashable` and return ``-1``. 416 This function receives special treatment when stored in a ``tp_hash`` slot, 417 allowing a type to explicitly indicate to the interpreter that it is not 418 hashable. 419 420 421.. c:function:: int PyObject_IsTrue(PyObject *o) 422 423 Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise. 424 This is equivalent to the Python expression ``not not o``. On failure, return 425 ``-1``. 426 427 428.. c:function:: int PyObject_Not(PyObject *o) 429 430 Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise. 431 This is equivalent to the Python expression ``not o``. On failure, return 432 ``-1``. 433 434 435.. c:function:: PyObject* PyObject_Type(PyObject *o) 436 437 .. index:: pair: built-in function; type 438 439 When *o* is non-``NULL``, returns a type object corresponding to the object type 440 of object *o*. On failure, raises :exc:`SystemError` and returns ``NULL``. This 441 is equivalent to the Python expression ``type(o)``. 442 This function creates a new :term:`strong reference` to the return value. 443 There's really no reason to use this 444 function instead of the :c:func:`Py_TYPE()` function, which returns a 445 pointer of type :c:expr:`PyTypeObject*`, except when a new 446 :term:`strong reference` is needed. 447 448 449.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type) 450 451 Return non-zero if the object *o* is of type *type* or a subtype of *type*, and 452 ``0`` otherwise. Both parameters must be non-``NULL``. 453 454 455.. c:function:: Py_ssize_t PyObject_Size(PyObject *o) 456 Py_ssize_t PyObject_Length(PyObject *o) 457 458 .. index:: pair: built-in function; len 459 460 Return the length of object *o*. If the object *o* provides either the sequence 461 and mapping protocols, the sequence length is returned. On error, ``-1`` is 462 returned. This is the equivalent to the Python expression ``len(o)``. 463 464 465.. c:function:: Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue) 466 467 Return an estimated length for the object *o*. First try to return its 468 actual length, then an estimate using :meth:`~object.__length_hint__`, and 469 finally return the default value. On error return ``-1``. This is the 470 equivalent to the Python expression ``operator.length_hint(o, defaultvalue)``. 471 472 .. versionadded:: 3.4 473 474 475.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key) 476 477 Return element of *o* corresponding to the object *key* or ``NULL`` on failure. 478 This is the equivalent of the Python expression ``o[key]``. 479 480 481.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v) 482 483 Map the object *key* to the value *v*. Raise an exception and 484 return ``-1`` on failure; return ``0`` on success. This is the 485 equivalent of the Python statement ``o[key] = v``. This function *does 486 not* steal a reference to *v*. 487 488 489.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key) 490 491 Remove the mapping for the object *key* from the object *o*. Return ``-1`` 492 on failure. This is equivalent to the Python statement ``del o[key]``. 493 494 495.. c:function:: PyObject* PyObject_Dir(PyObject *o) 496 497 This is equivalent to the Python expression ``dir(o)``, returning a (possibly 498 empty) list of strings appropriate for the object argument, or ``NULL`` if there 499 was an error. If the argument is ``NULL``, this is like the Python ``dir()``, 500 returning the names of the current locals; in this case, if no execution frame 501 is active then ``NULL`` is returned but :c:func:`PyErr_Occurred` will return false. 502 503 504.. c:function:: PyObject* PyObject_GetIter(PyObject *o) 505 506 This is equivalent to the Python expression ``iter(o)``. It returns a new 507 iterator for the object argument, or the object itself if the object is already 508 an iterator. Raises :exc:`TypeError` and returns ``NULL`` if the object cannot be 509 iterated. 510 511 512.. c:function:: PyObject* PyObject_GetAIter(PyObject *o) 513 514 This is the equivalent to the Python expression ``aiter(o)``. Takes an 515 :class:`AsyncIterable` object and returns an :class:`AsyncIterator` for it. 516 This is typically a new iterator but if the argument is an 517 :class:`AsyncIterator`, this returns itself. Raises :exc:`TypeError` and 518 returns ``NULL`` if the object cannot be iterated. 519 520 .. versionadded:: 3.10 521 522.. c:function:: void *PyObject_GetTypeData(PyObject *o, PyTypeObject *cls) 523 524 Get a pointer to subclass-specific data reserved for *cls*. 525 526 The object *o* must be an instance of *cls*, and *cls* must have been 527 created using negative :c:member:`PyType_Spec.basicsize`. 528 Python does not check this. 529 530 On error, set an exception and return ``NULL``. 531 532 .. versionadded:: 3.12 533 534.. c:function:: Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls) 535 536 Return the size of the instance memory space reserved for *cls*, i.e. the size of the 537 memory :c:func:`PyObject_GetTypeData` returns. 538 539 This may be larger than requested using :c:member:`-PyType_Spec.basicsize <PyType_Spec.basicsize>`; 540 it is safe to use this larger size (e.g. with :c:func:`!memset`). 541 542 The type *cls* **must** have been created using 543 negative :c:member:`PyType_Spec.basicsize`. 544 Python does not check this. 545 546 On error, set an exception and return a negative value. 547 548 .. versionadded:: 3.12 549 550.. c:function:: void *PyObject_GetItemData(PyObject *o) 551 552 Get a pointer to per-item data for a class with 553 :c:macro:`Py_TPFLAGS_ITEMS_AT_END`. 554 555 On error, set an exception and return ``NULL``. 556 :py:exc:`TypeError` is raised if *o* does not have 557 :c:macro:`Py_TPFLAGS_ITEMS_AT_END` set. 558 559 .. versionadded:: 3.12 560 561.. c:function:: int PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg) 562 563 Visit the managed dictionary of *obj*. 564 565 This function must only be called in a traverse function of the type which 566 has the :c:macro:`Py_TPFLAGS_MANAGED_DICT` flag set. 567 568 .. versionadded:: 3.13 569 570.. c:function:: void PyObject_ClearManagedDict(PyObject *obj) 571 572 Clear the managed dictionary of *obj*. 573 574 This function must only be called in a traverse function of the type which 575 has the :c:macro:`Py_TPFLAGS_MANAGED_DICT` flag set. 576 577 .. versionadded:: 3.13 578