Skip to content

Commit b142bf9

Browse files
committed
gh-108314: Add PyDict_ContainsString() function
Use PyDict_ContainsString() in pylifecycle.c and pythonrun.c.
1 parent adfc118 commit b142bf9

File tree

13 files changed

+91
-18
lines changed

13 files changed

+91
-18
lines changed

Doc/c-api/dict.rst

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,15 @@ Dictionary Objects
5555
This is equivalent to the Python expression ``key in p``.
5656
5757
58+
.. c:function:: int PyDict_ContainsString(PyObject *p, const char *key)
59+
60+
This is the same as :c:func:`PyDict_Contains`, but *key* is specified as a
61+
:c:expr:`const char*` UTF-8 encoded bytes string, rather than a
62+
:c:expr:`PyObject*`.
63+
64+
.. versionadded:: 3.13
65+
66+
5867
.. c:function:: PyObject* PyDict_Copy(PyObject *p)
5968
6069
Return a new dictionary that contains the same key-value pairs as *p*.
@@ -73,7 +82,7 @@ Dictionary Objects
7382
.. index:: single: PyUnicode_FromString()
7483
7584
Insert *val* into the dictionary *p* using *key* as a key. *key* should
76-
be a :c:expr:`const char*`. The key object is created using
85+
be a :c:expr:`const char*` UTF-8 encoded bytes string. The key object is created using
7786
``PyUnicode_FromString(key)``. Return ``0`` on success or ``-1`` on
7887
failure. This function *does not* steal a reference to *val*.
7988
@@ -88,7 +97,8 @@ Dictionary Objects
8897
8998
.. c:function:: int PyDict_DelItemString(PyObject *p, const char *key)
9099
91-
Remove the entry in dictionary *p* which has a key specified by the string *key*.
100+
Remove the entry in dictionary *p* which has a key specified by the UTF-8
101+
encoded bytes string *key*.
92102
If *key* is not in the dictionary, :exc:`KeyError` is raised.
93103
Return ``0`` on success or ``-1`` on failure.
94104
@@ -136,7 +146,8 @@ Dictionary Objects
136146
.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
137147
138148
This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a
139-
:c:expr:`const char*`, rather than a :c:expr:`PyObject*`.
149+
:c:expr:`const char*` UTF-8 encoded bytes string, rather than a
150+
:c:expr:`PyObject*`.
140151
141152
.. note::
142153
@@ -150,7 +161,8 @@ Dictionary Objects
150161
.. c:function:: int PyDict_GetItemStringRef(PyObject *p, const char *key, PyObject **result)
151162
152163
Similar than :c:func:`PyDict_GetItemRef`, but *key* is specified as a
153-
:c:expr:`const char*`, rather than a :c:expr:`PyObject*`.
164+
:c:expr:`const char*` UTF-8 encoded bytes string, rather than a
165+
:c:expr:`PyObject*`.
154166
155167
.. versionadded:: 3.13
156168

Doc/data/stable_abi.dat

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Doc/whatsnew/3.13.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,11 @@ New Features
862862
not needed.
863863
(Contributed by Victor Stinner in :gh:`106004`.)
864864

865+
* Added :c:func:`PyDict_ContainsString` function: same as
866+
:c:func:`PyDict_Contains`, but *key* is specified as a :c:expr:`const char*`
867+
UTF-8 encoded bytes string, rather than a :c:expr:`PyObject*`.
868+
(Contributed by Victor Stinner in :gh:`108314`.)
869+
865870
* Add :c:func:`Py_IsFinalizing` function: check if the main Python interpreter is
866871
:term:`shutting down <interpreter shutdown>`.
867872
(Contributed by Victor Stinner in :gh:`108014`.)

Include/dictobject.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
3232
PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
3333
PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
3434
PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
35+
PyAPI_FUNC(int) PyDict_ContainsString(PyObject *mp, const char *key);
3536

3637
/* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
3738
PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);

Lib/test/test_capi/test_dict.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,20 @@ def test_dict_contains(self):
213213
# CRASHES contains(42, 'a')
214214
# CRASHES contains(NULL, 'a')
215215

216+
def test_dict_contains_string(self):
217+
contains_string = _testcapi.dict_containsstring
218+
dct = {'a': 1, '\U0001f40d': 2}
219+
self.assertTrue(contains_string(dct, b'a'))
220+
self.assertFalse(contains_string(dct, b'b'))
221+
self.assertTrue(contains_string(dct, '\U0001f40d'.encode()))
222+
223+
dct2 = DictSubclass(dct)
224+
self.assertTrue(contains_string(dct2, b'a'))
225+
self.assertFalse(contains_string(dct2, b'b'))
226+
227+
# CRASHES contains({}, NULL)
228+
# CRASHES contains(NULL, b'a')
229+
216230
def test_dict_setitem(self):
217231
setitem = _testcapi.dict_setitem
218232
dct = {}

Lib/test/test_stable_abi_ctypes.py

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Add :c:func:`PyDict_ContainsString` function: same as
2+
:c:func:`PyDict_Contains`, but *key* is specified as a :c:expr:`const char*`
3+
UTF-8 encoded bytes string, rather than a :c:expr:`PyObject*`.
4+
Patch by Victor Stinner.

Misc/stable_abi.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2450,3 +2450,5 @@
24502450
added = '3.13'
24512451
[function.PyDict_GetItemStringRef]
24522452
added = '3.13'
2453+
[function.PyDict_ContainsString]
2454+
added = '3.13'

Modules/_testcapi/dict.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,19 @@ dict_contains(PyObject *self, PyObject *args)
7474
RETURN_INT(PyDict_Contains(obj, key));
7575
}
7676

77+
static PyObject *
78+
dict_containsstring(PyObject *self, PyObject *args)
79+
{
80+
PyObject *obj;
81+
const char *key;
82+
Py_ssize_t size;
83+
if (!PyArg_ParseTuple(args, "Oz#", &obj, &key, &size)) {
84+
return NULL;
85+
}
86+
NULLABLE(obj);
87+
RETURN_INT(PyDict_ContainsString(obj, key));
88+
}
89+
7790
static PyObject *
7891
dict_size(PyObject *self, PyObject *obj)
7992
{
@@ -349,6 +362,7 @@ static PyMethodDef test_methods[] = {
349362
{"dict_getitemref", dict_getitemref, METH_VARARGS},
350363
{"dict_getitemstringref", dict_getitemstringref, METH_VARARGS},
351364
{"dict_contains", dict_contains, METH_VARARGS},
365+
{"dict_containsstring", dict_containsstring, METH_VARARGS},
352366
{"dict_setitem", dict_setitem, METH_VARARGS},
353367
{"dict_setitemstring", dict_setitemstring, METH_VARARGS},
354368
{"dict_delitem", dict_delitem, METH_VARARGS},

Objects/dictobject.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3741,6 +3741,18 @@ PyDict_Contains(PyObject *op, PyObject *key)
37413741
return (ix != DKIX_EMPTY && value != NULL);
37423742
}
37433743

3744+
int
3745+
PyDict_ContainsString(PyObject *op, const char *key)
3746+
{
3747+
PyObject *key_obj = PyUnicode_FromString(key);
3748+
if (key_obj == NULL) {
3749+
return -1;
3750+
}
3751+
int res = PyDict_Contains(op, key_obj);
3752+
Py_DECREF(key_obj);
3753+
return res;
3754+
}
3755+
37443756
/* Internal version of PyDict_Contains used when the hash value is already known */
37453757
int
37463758
_PyDict_Contains_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)

PC/python3dll.c

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Python/pylifecycle.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2208,10 +2208,11 @@ add_main_module(PyInterpreterState *interp)
22082208
}
22092209
Py_DECREF(ann_dict);
22102210

2211-
if (_PyDict_GetItemStringWithError(d, "__builtins__") == NULL) {
2212-
if (PyErr_Occurred()) {
2213-
return _PyStatus_ERR("Failed to test __main__.__builtins__");
2214-
}
2211+
int has_builtins = PyDict_ContainsString(d, "__builtins__");
2212+
if (has_builtins < 0) {
2213+
return _PyStatus_ERR("Failed to test __main__.__builtins__");
2214+
}
2215+
if (!has_builtins) {
22152216
PyObject *bimod = PyImport_ImportModule("builtins");
22162217
if (bimod == NULL) {
22172218
return _PyStatus_ERR("Failed to retrieve builtins module");

Python/pythonrun.c

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -413,10 +413,11 @@ _PyRun_SimpleFileObject(FILE *fp, PyObject *filename, int closeit,
413413
PyObject *dict = PyModule_GetDict(main_module); // borrowed ref
414414

415415
int set_file_name = 0;
416-
if (_PyDict_GetItemStringWithError(dict, "__file__") == NULL) {
417-
if (PyErr_Occurred()) {
418-
goto done;
419-
}
416+
int has_file = PyDict_ContainsString(dict, "__file__");
417+
if (has_file < 0) {
418+
goto done;
419+
}
420+
if (!has_file) {
420421
if (PyDict_SetItemString(dict, "__file__", filename) < 0) {
421422
goto done;
422423
}
@@ -1713,12 +1714,16 @@ run_eval_code_obj(PyThreadState *tstate, PyCodeObject *co, PyObject *globals, Py
17131714
_PyRuntime.signals.unhandled_keyboard_interrupt = 0;
17141715

17151716
/* Set globals['__builtins__'] if it doesn't exist */
1716-
if (globals != NULL && _PyDict_GetItemStringWithError(globals, "__builtins__") == NULL) {
1717-
if (PyErr_Occurred() ||
1718-
PyDict_SetItemString(globals, "__builtins__",
1719-
tstate->interp->builtins) < 0)
1720-
{
1721-
return NULL;
1717+
if (globals != NULL) {
1718+
int has_builtins = PyDict_ContainsString(globals, "__builtins__");
1719+
if (has_builtins < 0) {
1720+
return NULL;
1721+
}
1722+
if (!has_builtins) {
1723+
if (PyDict_SetItemString(globals, "__builtins__",
1724+
tstate->interp->builtins) < 0) {
1725+
return NULL;
1726+
}
17221727
}
17231728
}
17241729

0 commit comments

Comments
 (0)