Skip to content

Conversation

@serhiy-storchaka
Copy link
Member

@serhiy-storchaka serhiy-storchaka commented Oct 26, 2020

Use PyDict_Contains and PyDict_SetDefault if appropriate.

https://bugs.python.org/issue42152

… is not used.

Use PyDict_Contains and PyDict_SetDefault if appropriate.
int r = _PyDict_ContainsId(d, &PyId___builtins__);
if (r == 0) {
r = _PyDict_SetItemId(d, &PyId___builtins__,
PyEval_GetBuiltins());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PyEval_GetBuiltins() is cheap function so we can use PyDict_SetDefault() here, and builtin_eval_impl, builtin_exec_impl if you want to.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no _PyDict_SetDefaultId() and I do not want to introduce it just for these three cases. Using PyDict_SetDefault() + _PyUnicode_FromId() will not make large difference:

    int r = _PyDict_ContainsId(d, &PyId___builtins__);
    if (r == 0) {
        r = _PyDict_SetItemId(d, &PyId___builtins__,
                              PyEval_GetBuiltins());
    }
    if (r < 0) {
        remove_module(tstate, name);
        return NULL;
    }

vs

    PyObject *tmp = _PyUnicode_FromId(&PyId___builtins__);
    if (tmp != NULL) {
        tmp = PyDict_SetDefault(d, tmp, PyEval_GetBuiltins());
    }
    if (tmp == NULL) {
        remove_module(tstate, name);
        return NULL;
    }

Copy link
Member

@methane methane left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks very nice.

@markshannon
Copy link
Member

LGTM.
Nice improvement in code clarity.

The PR title say this is an optimization, but I don't see that as relevant or justified.
Probably best to describe this as a code quality improvement if adding a NEWS item.

@serhiy-storchaka serhiy-storchaka merged commit b510e10 into python:master Oct 26, 2020
@serhiy-storchaka serhiy-storchaka deleted the use-PyDict_Contains branch October 26, 2020 10:48
adorilson pushed a commit to adorilson/cpython that referenced this pull request Mar 13, 2021
…ythonGH-22986)

If PyDict_GetItemWithError is only used to check whether the key is in dict,
it is better to use PyDict_Contains instead.

And if it is used in combination with PyDict_SetItem, PyDict_SetDefault can
replace the combination.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants