Skip to content

[C API] Add PyFrozenDict_New() to the limited C API 3.16 #162047

Open

Description

@vstinner

PEP 814 – Add frozendict built-in type added 5 functions to the C API in Python 3.15. I would like to add them to the limited C API 3.16. I don't think that these functions expose any implementation detail. The Check macros just access to PyFrozenDict_Type built-in static type.

Currently, the workaround for missing PyFrozenDict_New(iterable) function is to get the frozendict type from builtins:

    // PyFrozenDict_New() is not part of the limited C API.
    // Instead, get the built-in "frozendict" type and call frozendict(iterable).
    PyObject *builtins = PyEval_GetFrameBuiltins();
    assert(builtins != NULL);
    PyObject *frozendict_type = PyMapping_GetItemString(builtins, "frozendict");
    Py_DECREF(builtins);
    if (frozendict_type == NULL) {
        return NULL;
    }

    PyObject *res = PyObject_CallOneArg(frozendict_type, iterable);
    Py_DECREF(frozendict_type);

It's less efficient since it has to decode "frozendict" bytes string from UTF-8 to build a temporary Python str object, and lookup for the key in builtins dictionary.

Note: by the way, it can return the wrong type if builtins.frozendict is overridden.

I had to write such code to implement PyDict_AsFrozenDictAndClear() for Python 3.15 in the pythoncapi-compat project.

I suppose that PyFrozenDict_CheckExact() can be implemented in a similar way which would also be inefficient, whereas the macro is implement as efficient Py_IS_TYPE((op), &PyFrozenDict_Type).

Linked PRs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions