Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add PyMapping_GetOptionalItem() #106307

Closed
Closed
Labels
@serhiy-storchaka

Description

@serhiy-storchaka

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:

     PyObject *m;-    if (PyDict_CheckExact(modules)) {-        m = Py_XNewRef(PyDict_GetItemWithError(modules, name));-    }-    else {-        m = PyObject_GetItem(modules, name);-        if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {-            _PyErr_Clear(tstate);-        }-    }-    if (_PyErr_Occurred(tstate)) {+    if (_PyMapping_LookupItem(modules, name, &m) < 0) {         return NULL;     }

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp