-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add PyMapping_GetOptionalItem() #106307
Comments
Replacement of PyObject_GetItem() which doesn't raise KeyError. int _PyMapping_LookupItem(PyObject *obj, PyObject *key, PyObject **result) Return 1 and set *result != NULL if a key is found. Return 0 and set *result == NULL if a key is not found; a KeyError is silenced. Return -1 and set *result == NULL if an error other than KeyError is raised.
Replacement of PyObject_GetItem() which doesn't raise KeyError. int _PyMapping_LookupItem(PyObject *obj, PyObject *key, PyObject **result) Return 1 and set *result != NULL if a key is found. Return 0 and set *result == NULL if a key is not found; a KeyError is silenced. Return -1 and set *result == NULL if an error other than KeyError is raised.
Why should this be a private API? It seems like for many uses it's simply better, and it doesn't seem to expose any internal implementation details that we would be hesitant to support. I think |
This is an interesting idea. If make |
Also add PyMapping_GetOptionalItemString() function.
I added the 2 functions to pythoncapi-compat: python/pythoncapi-compat@7515dae |
The resulting pointer was not set to NULL if the creation of a temporary string object was failed. The tests were also missed due to oversight.
The resulting pointer was not set to NULL if the creation of a temporary string object was failed. The tests were also missed due to oversight.
PyObject_GetItem()
raises a KeyError if the key is not found in a mapping. In some cases it should be treated as any other error, but in other cases it should be caught and suppressed. The repeating pattern ofPyObject_GetItem()
followed byPyErr_ExceptionMatches(PyExc_KeyError)
andPyErr_Clear()
occurs 7 times inPython/bytecodes.c
and at least 5 times in other files.I propose to add private helper
_PyMapping_LookupItem()
which combines these three calls to make the code clearer. It also has a special case for exact dict, so eliminates even more repeating code. For example:The interface of
_PyMapping_LookupItem()
is very similar to other private helper_PyObject_LookupAttr()
(see #76752) and to a proposed new C API for PyDict (see #106004).Linked PRs
The text was updated successfully, but these errors were encountered: