Debian Codegraph @

Doc/c-api/dict.rst

raw
1 .. highlight:: c
2
3 .. _dictobjects:
4
5 Dictionary Objects
6 ------------------
7
8 .. index:: pair: object; dictionary
9
10
11 .. c:type:: PyDictObject
12
13 This subtype of :c:type:`PyObject` represents a Python dictionary object.
14
15
16 .. c:var:: PyTypeObject PyDict_Type
17
18 This instance of :c:type:`PyTypeObject` represents the Python dictionary
19 type. This is the same object as :class:`dict` in the Python layer.
20
21
22 .. c:function:: int PyDict_Check(PyObject *p)
23
24 Return true if *p* is a dict object or an instance of a subtype of the dict
25 type. This function always succeeds.
26
27
28 .. c:function:: int PyDict_CheckExact(PyObject *p)
29
30 Return true if *p* is a dict object, but not an instance of a subtype of
31 the dict type. This function always succeeds.
32
33
34 .. c:function:: PyObject* PyDict_New()
35
36 Return a new empty dictionary, or ``NULL`` on failure.
37
38
39 .. c:function:: PyObject* PyDictProxy_New(PyObject *mapping)
40
41 Return a :class:`types.MappingProxyType` object for a mapping which
42 enforces read-only behavior. This is normally used to create a view to
43 prevent modification of the dictionary for non-dynamic class types.
44
45
46 .. c:var:: PyTypeObject PyDictProxy_Type
47
48 The type object for mapping proxy objects created by
49 :c:func:`PyDictProxy_New` and for the read-only ``__dict__`` attribute
50 of many built-in types. A :c:type:`PyDictProxy_Type` instance provides a
51 dynamic, read-only view of an underlying dictionary: changes to the
52 underlying dictionary are reflected in the proxy, but the proxy itself
53 does not support mutation operations. This corresponds to
54 :class:`types.MappingProxyType` in Python.
55
56
57 .. c:function:: void PyDict_Clear(PyObject *p)
58
59 Empty an existing dictionary of all key-value pairs.
60
61
62 .. c:function:: int PyDict_Contains(PyObject *p, PyObject *key)
63
64 Determine if dictionary *p* contains *key*. If an item in *p* matches
65 *key*, return ``1``, otherwise return ``0``. On error, return ``-1``.
66 This is equivalent to the Python expression ``key in p``.
67
68
69 .. c:function:: int PyDict_ContainsString(PyObject *p, const char *key)
70
71 This is the same as :c:func:`PyDict_Contains`, but *key* is specified as a
72 :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
73 :c:expr:`PyObject*`.
74
75 .. versionadded:: 3.13
76
77
78 .. c:function:: PyObject* PyDict_Copy(PyObject *p)
79
80 Return a new dictionary that contains the same key-value pairs as *p*.
81
82
83 .. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
84
85 Insert *val* into the dictionary *p* with a key of *key*. *key* must be
86 :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return
87 ``0`` on success or ``-1`` on failure. This function *does not* steal a
88 reference to *val*.
89
90
91 .. c:function:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
92
93 This is the same as :c:func:`PyDict_SetItem`, but *key* is
94 specified as a :c:expr:`const char*` UTF-8 encoded bytes string,
95 rather than a :c:expr:`PyObject*`.
96
97
98 .. c:function:: int PyDict_DelItem(PyObject *p, PyObject *key)
99
100 Remove the entry in dictionary *p* with key *key*. *key* must be :term:`hashable`;
101 if it isn't, :exc:`TypeError` is raised.
102 If *key* is not in the dictionary, :exc:`KeyError` is raised.
103 Return ``0`` on success or ``-1`` on failure.
104
105
106 .. c:function:: int PyDict_DelItemString(PyObject *p, const char *key)
107
108 This is the same as :c:func:`PyDict_DelItem`, but *key* is
109 specified as a :c:expr:`const char*` UTF-8 encoded bytes string,
110 rather than a :c:expr:`PyObject*`.
111
112
113 .. c:function:: int PyDict_GetItemRef(PyObject *p, PyObject *key, PyObject **result)
114
115 Return a new :term:`strong reference` to the object from dictionary *p*
116 which has a key *key*:
117
118 * If the key is present, set *\*result* to a new :term:`strong reference`
119 to the value and return ``1``.
120 * If the key is missing, set *\*result* to ``NULL`` and return ``0``.
121 * On error, raise an exception and return ``-1``.
122
123 .. versionadded:: 3.13
124
125 See also the :c:func:`PyObject_GetItem` function.
126
127
128 .. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
129
130 Return a :term:`borrowed reference` to the object from dictionary *p* which
131 has a key *key*. Return ``NULL`` if the key *key* is missing *without*
132 setting an exception.
133
134 .. note::
135
136 Exceptions that occur while this calls :meth:`~object.__hash__` and
137 :meth:`~object.__eq__` methods are silently ignored.
138 Prefer the :c:func:`PyDict_GetItemWithError` function instead.
139
140 .. versionchanged:: 3.10
141 Calling this API without :term:`GIL` held had been allowed for historical
142 reason. It is no longer allowed.
143
144
145 .. c:function:: PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key)
146
147 Variant of :c:func:`PyDict_GetItem` that does not suppress
148 exceptions. Return ``NULL`` **with** an exception set if an exception
149 occurred. Return ``NULL`` **without** an exception set if the key
150 wasn't present.
151
152
153 .. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
154
155 This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a
156 :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
157 :c:expr:`PyObject*`.
158
159 .. note::
160
161 Exceptions that occur while this calls :meth:`~object.__hash__` and
162 :meth:`~object.__eq__` methods or while creating the temporary :class:`str`
163 object are silently ignored.
164 Prefer using the :c:func:`PyDict_GetItemWithError` function with your own
165 :c:func:`PyUnicode_FromString` *key* instead.
166
167
168 .. c:function:: int PyDict_GetItemStringRef(PyObject *p, const char *key, PyObject **result)
169
170 Similar to :c:func:`PyDict_GetItemRef`, but *key* is specified as a
171 :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
172 :c:expr:`PyObject*`.
173
174 .. versionadded:: 3.13
175
176
177 .. c:function:: PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
178
179 This is the same as the Python-level :meth:`dict.setdefault`. If present, it
180 returns the value corresponding to *key* from the dictionary *p*. If the key
181 is not in the dict, it is inserted with value *defaultobj* and *defaultobj*
182 is returned. This function evaluates the hash function of *key* only once,
183 instead of evaluating it independently for the lookup and the insertion.
184
185 .. versionadded:: 3.4
186
187
188 .. c:function:: int PyDict_SetDefaultRef(PyObject *p, PyObject *key, PyObject *default_value, PyObject **result)
189
190 Inserts *default_value* into the dictionary *p* with a key of *key* if the
191 key is not already present in the dictionary. If *result* is not ``NULL``,
192 then *\*result* is set to a :term:`strong reference` to either
193 *default_value*, if the key was not present, or the existing value, if *key*
194 was already present in the dictionary.
195 Returns ``1`` if the key was present and *default_value* was not inserted,
196 or ``0`` if the key was not present and *default_value* was inserted.
197 On failure, returns ``-1``, sets an exception, and sets ``*result``
198 to ``NULL``.
199
200 For clarity: if you have a strong reference to *default_value* before
201 calling this function, then after it returns, you hold a strong reference
202 to both *default_value* and *\*result* (if it's not ``NULL``).
203 These may refer to the same object: in that case you hold two separate
204 references to it.
205
206 .. versionadded:: 3.13
207
208
209 .. c:function:: int PyDict_Pop(PyObject *p, PyObject *key, PyObject **result)
210
211 Remove *key* from dictionary *p* and optionally return the removed value.
212 Do not raise :exc:`KeyError` if the key is missing.
213
214 - If the key is present, set *\*result* to a new reference to the removed
215 value if *result* is not ``NULL``, and return ``1``.
216 - If the key is missing, set *\*result* to ``NULL`` if *result* is not
217 ``NULL``, and return ``0``.
218 - On error, raise an exception and return ``-1``.
219
220 Similar to :meth:`dict.pop`, but without the default value and
221 not raising :exc:`KeyError` if the key is missing.
222
223 .. versionadded:: 3.13
224
225
226 .. c:function:: int PyDict_PopString(PyObject *p, const char *key, PyObject **result)
227
228 Similar to :c:func:`PyDict_Pop`, but *key* is specified as a
229 :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
230 :c:expr:`PyObject*`.
231
232 .. versionadded:: 3.13
233
234
235 .. c:function:: PyObject* PyDict_Items(PyObject *p)
236
237 Return a :c:type:`PyListObject` containing all the items from the dictionary.
238
239
240 .. c:function:: PyObject* PyDict_Keys(PyObject *p)
241
242 Return a :c:type:`PyListObject` containing all the keys from the dictionary.
243
244
245 .. c:function:: PyObject* PyDict_Values(PyObject *p)
246
247 Return a :c:type:`PyListObject` containing all the values from the dictionary
248 *p*.
249
250
251 .. c:function:: Py_ssize_t PyDict_Size(PyObject *p)
252
253 .. index:: pair: built-in function; len
254
255 Return the number of items in the dictionary. This is equivalent to
256 ``len(p)`` on a dictionary.
257
258
259 .. c:function:: Py_ssize_t PyDict_GET_SIZE(PyObject *p)
260
261 Similar to :c:func:`PyDict_Size`, but without error checking.
262
263
264 .. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
265
266 Iterate over all key-value pairs in the dictionary *p*. The
267 :c:type:`Py_ssize_t` referred to by *ppos* must be initialized to ``0``
268 prior to the first call to this function to start the iteration; the
269 function returns true for each pair in the dictionary, and false once all
270 pairs have been reported. The parameters *pkey* and *pvalue* should either
271 point to :c:expr:`PyObject*` variables that will be filled in with each key
272 and value, respectively, or may be ``NULL``. Any references returned through
273 them are borrowed. *ppos* should not be altered during iteration. Its
274 value represents offsets within the internal dictionary structure, and
275 since the structure is sparse, the offsets are not consecutive.
276
277 For example::
278
279 PyObject *key, *value;
280 Py_ssize_t pos = 0;
281
282 while (PyDict_Next(self->dict, &pos, &key, &value)) {
283 /* do something interesting with the values... */
284 ...
285 }
286
287 The dictionary *p* should not be mutated during iteration. It is safe to
288 modify the values of the keys as you iterate over the dictionary, but only
289 so long as the set of keys does not change. For example::
290
291 PyObject *key, *value;
292 Py_ssize_t pos = 0;
293
294 while (PyDict_Next(self->dict, &pos, &key, &value)) {
295 long i = PyLong_AsLong(value);
296 if (i == -1 && PyErr_Occurred()) {
297 return -1;
298 }
299 PyObject *o = PyLong_FromLong(i + 1);
300 if (o == NULL)
301 return -1;
302 if (PyDict_SetItem(self->dict, key, o) < 0) {
303 Py_DECREF(o);
304 return -1;
305 }
306 Py_DECREF(o);
307 }
308
309 The function is not thread-safe in the :term:`free-threaded <free threading>`
310 build without external synchronization. You can use
311 :c:macro:`Py_BEGIN_CRITICAL_SECTION` to lock the dictionary while iterating
312 over it::
313
314 Py_BEGIN_CRITICAL_SECTION(self->dict);
315 while (PyDict_Next(self->dict, &pos, &key, &value)) {
316 ...
317 }
318 Py_END_CRITICAL_SECTION();
319
320
321 .. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
322
323 Iterate over mapping object *b* adding key-value pairs to dictionary *a*.
324 *b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys`
325 and :c:func:`PyObject_GetItem`. If *override* is true, existing pairs in *a*
326 will be replaced if a matching key is found in *b*, otherwise pairs will
327 only be added if there is not a matching key in *a*. Return ``0`` on
328 success or ``-1`` if an exception was raised.
329
330
331 .. c:function:: int PyDict_Update(PyObject *a, PyObject *b)
332
333 This is the same as ``PyDict_Merge(a, b, 1)`` in C, and is similar to
334 ``a.update(b)`` in Python except that :c:func:`PyDict_Update` doesn't fall
335 back to the iterating over a sequence of key value pairs if the second
336 argument has no "keys" attribute. Return ``0`` on success or ``-1`` if an
337 exception was raised.
338
339
340 .. c:function:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
341
342 Update or merge into dictionary *a*, from the key-value pairs in *seq2*.
343 *seq2* must be an iterable object producing iterable objects of length 2,
344 viewed as key-value pairs. In case of duplicate keys, the last wins if
345 *override* is true, else the first wins. Return ``0`` on success or ``-1``
346 if an exception was raised. Equivalent Python (except for the return
347 value)::
348
349 def PyDict_MergeFromSeq2(a, seq2, override):
350 for key, value in seq2:
351 if override or key not in a:
352 a[key] = value
353
354 .. c:function:: int PyDict_AddWatcher(PyDict_WatchCallback callback)
355
356 Register *callback* as a dictionary watcher. Return a non-negative integer
357 id which must be passed to future calls to :c:func:`PyDict_Watch`. In case
358 of error (e.g. no more watcher IDs available), return ``-1`` and set an
359 exception.
360
361 .. versionadded:: 3.12
362
363 .. c:function:: int PyDict_ClearWatcher(int watcher_id)
364
365 Clear watcher identified by *watcher_id* previously returned from
366 :c:func:`PyDict_AddWatcher`. Return ``0`` on success, ``-1`` on error (e.g.
367 if the given *watcher_id* was never registered.)
368
369 .. versionadded:: 3.12
370
371 .. c:function:: int PyDict_Watch(int watcher_id, PyObject *dict)
372
373 Mark dictionary *dict* as watched. The callback granted *watcher_id* by
374 :c:func:`PyDict_AddWatcher` will be called when *dict* is modified or
375 deallocated. Return ``0`` on success or ``-1`` on error.
376
377 .. versionadded:: 3.12
378
379 .. c:function:: int PyDict_Unwatch(int watcher_id, PyObject *dict)
380
381 Mark dictionary *dict* as no longer watched. The callback granted
382 *watcher_id* by :c:func:`PyDict_AddWatcher` will no longer be called when
383 *dict* is modified or deallocated. The dict must previously have been
384 watched by this watcher. Return ``0`` on success or ``-1`` on error.
385
386 .. versionadded:: 3.12
387
388 .. c:type:: PyDict_WatchEvent
389
390 Enumeration of possible dictionary watcher events: ``PyDict_EVENT_ADDED``,
391 ``PyDict_EVENT_MODIFIED``, ``PyDict_EVENT_DELETED``, ``PyDict_EVENT_CLONED``,
392 ``PyDict_EVENT_CLEARED``, or ``PyDict_EVENT_DEALLOCATED``.
393
394 .. versionadded:: 3.12
395
396 .. c:type:: int (*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject *new_value)
397
398 Type of a dict watcher callback function.
399
400 If *event* is ``PyDict_EVENT_CLEARED`` or ``PyDict_EVENT_DEALLOCATED``, both
401 *key* and *new_value* will be ``NULL``. If *event* is ``PyDict_EVENT_ADDED``
402 or ``PyDict_EVENT_MODIFIED``, *new_value* will be the new value for *key*.
403 If *event* is ``PyDict_EVENT_DELETED``, *key* is being deleted from the
404 dictionary and *new_value* will be ``NULL``.
405
406 ``PyDict_EVENT_CLONED`` occurs when *dict* was previously empty and another
407 dict is merged into it. To maintain efficiency of this operation, per-key
408 ``PyDict_EVENT_ADDED`` events are not issued in this case; instead a
409 single ``PyDict_EVENT_CLONED`` is issued, and *key* will be the source
410 dictionary.
411
412 The callback may inspect but must not modify *dict*; doing so could have
413 unpredictable effects, including infinite recursion. Do not trigger Python
414 code execution in the callback, as it could modify the dict as a side effect.
415
416 If *event* is ``PyDict_EVENT_DEALLOCATED``, taking a new reference in the
417 callback to the about-to-be-destroyed dictionary will resurrect it and
418 prevent it from being freed at this time. When the resurrected object is
419 destroyed later, any watcher callbacks active at that time will be called
420 again.
421
422 Callbacks occur before the notified modification to *dict* takes place, so
423 the prior state of *dict* can be inspected.
424
425 If the callback sets an exception, it must return ``-1``; this exception will
426 be printed as an unraisable exception using :c:func:`PyErr_WriteUnraisable`.
427 Otherwise it should return ``0``.
428
429 There may already be a pending exception set on entry to the callback. In
430 this case, the callback should return ``0`` with the same exception still
431 set. This means the callback may not call any other API that can set an
432 exception unless it saves and clears the exception state first, and restores
433 it before returning.
434
435 .. versionadded:: 3.12
436
437
438 Dictionary View Objects
439 ^^^^^^^^^^^^^^^^^^^^^^^
440
441 .. c:function:: int PyDictViewSet_Check(PyObject *op)
442
443 Return true if *op* is a view of a set inside a dictionary. This is currently
444 equivalent to :c:expr:`PyDictKeys_Check(op) || PyDictItems_Check(op)`. This
445 function always succeeds.
446
447
448 .. c:var:: PyTypeObject PyDictKeys_Type
449
450 Type object for a view of dictionary keys. In Python, this is the type of
451 the object returned by :meth:`dict.keys`.
452
453
454 .. c:function:: int PyDictKeys_Check(PyObject *op)
455
456 Return true if *op* is an instance of a dictionary keys view. This function
457 always succeeds.
458
459
460 .. c:var:: PyTypeObject PyDictValues_Type
461
462 Type object for a view of dictionary values. In Python, this is the type of
463 the object returned by :meth:`dict.values`.
464
465
466 .. c:function:: int PyDictValues_Check(PyObject *op)
467
468 Return true if *op* is an instance of a dictionary values view. This function
469 always succeeds.
470
471
472 .. c:var:: PyTypeObject PyDictItems_Type
473
474 Type object for a view of dictionary items. In Python, this is the type of
475 the object returned by :meth:`dict.items`.
476
477
478 .. c:function:: int PyDictItems_Check(PyObject *op)
479
480 Return true if *op* is an instance of a dictionary items view. This function
481 always succeeds.
482
483
484 Ordered Dictionaries
485 ^^^^^^^^^^^^^^^^^^^^
486
487 Python's C API provides interface for :class:`collections.OrderedDict` from C.
488 Since Python 3.7, dictionaries are ordered by default, so there is usually
489 little need for these functions; prefer ``PyDict*`` where possible.
490
491
492 .. c:var:: PyTypeObject PyODict_Type
493
494 Type object for ordered dictionaries. This is the same object as
495 :class:`collections.OrderedDict` in the Python layer.
496
497
498 .. c:function:: int PyODict_Check(PyObject *od)
499
500 Return true if *od* is an ordered dictionary object or an instance of a
501 subtype of the :class:`~collections.OrderedDict` type. This function
502 always succeeds.
503
504
505 .. c:function:: int PyODict_CheckExact(PyObject *od)
506
507 Return true if *od* is an ordered dictionary object, but not an instance of
508 a subtype of the :class:`~collections.OrderedDict` type.
509 This function always succeeds.
510
511
512 .. c:var:: PyTypeObject PyODictKeys_Type
513
514 Analogous to :c:type:`PyDictKeys_Type` for ordered dictionaries.
515
516
517 .. c:var:: PyTypeObject PyODictValues_Type
518
519 Analogous to :c:type:`PyDictValues_Type` for ordered dictionaries.
520
521
522 .. c:var:: PyTypeObject PyODictItems_Type
523
524 Analogous to :c:type:`PyDictItems_Type` for ordered dictionaries.
525
526
527 .. c:function:: PyObject *PyODict_New(void)
528
529 Return a new empty ordered dictionary, or ``NULL`` on failure.
530
531 This is analogous to :c:func:`PyDict_New`.
532
533
534 .. c:function:: int PyODict_SetItem(PyObject *od, PyObject *key, PyObject *value)
535
536 Insert *value* into the ordered dictionary *od* with a key of *key*.
537 Return ``0`` on success or ``-1`` with an exception set on failure.
538
539 This is analogous to :c:func:`PyDict_SetItem`.
540
541
542 .. c:function:: int PyODict_DelItem(PyObject *od, PyObject *key)
543
544 Remove the entry in the ordered dictionary *od* with key *key*.
545 Return ``0`` on success or ``-1`` with an exception set on failure.
546
547 This is analogous to :c:func:`PyDict_DelItem`.
548
549
550 These are :term:`soft deprecated` aliases to ``PyDict`` APIs:
551
552
553 .. list-table::
554 :widths: auto
555 :header-rows: 1
556
557 * * ``PyODict``
558 * ``PyDict``
559 * * .. c:macro:: PyODict_GetItem(od, key)
560 * :c:func:`PyDict_GetItem`
561 * * .. c:macro:: PyODict_GetItemWithError(od, key)
562 * :c:func:`PyDict_GetItemWithError`
563 * * .. c:macro:: PyODict_GetItemString(od, key)
564 * :c:func:`PyDict_GetItemString`
565 * * .. c:macro:: PyODict_Contains(od, key)
566 * :c:func:`PyDict_Contains`
567 * * .. c:macro:: PyODict_Size(od)
568 * :c:func:`PyDict_Size`
569 * * .. c:macro:: PyODict_SIZE(od)
570 * :c:func:`PyDict_GET_SIZE`