Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Doc/c-api/dict.rst
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,23 @@ Dictionary objects
modified by another thread.
.. c:function:: PyObject* PyDict_AsFrozenDictAndClear(PyObject *dict)
Return a new :class:`frozendict` created
from the existing :class:`dict` instance.
Transfers all keys and values from *dict*
to the newly allocated :class:`!frozendict`.
Clears the input *dict* on success.
Returns ``NULL`` with the exception set on error.
.. impl-detail::
Works with O(1) complexity.
.. versionadded:: next
.. c:function:: int PyDict_AddWatcher(PyDict_WatchCallback callback)
Register *callback* as a dictionary watcher. Return a non-negative integer
Expand Down
4 changes: 3 additions & 1 deletion Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,9 @@ C API changes
New features
------------

* TODO
* Add a new way to efficitly create :class:`frozendict` instance
from existing :class:`dict` instances: :c:func:`PyDict_AsFrozenDictAndClear`.


Porting to Python 3.16
----------------------
Expand Down
4 changes: 4 additions & 0 deletions Include/cpython/dictobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,7 @@ PyAPI_FUNC(int) PyDict_Unwatch(int watcher_id, PyObject* dict);

// Create a frozendict. Create an empty dictionary if iterable is NULL.
PyAPI_FUNC(PyObject*) PyFrozenDict_New(PyObject *iterable);

// Create a frozendict from existing `PyDictObject`.
// Transfers existing keys and values.
PyAPI_FUNC(PyObject*) PyDict_AsFrozenDictAndClear(PyObject *dict);
31 changes: 31 additions & 0 deletions Lib/test/test_capi/test_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,37 @@ def test_dict_popstring(self):
# CRASHES dict_popstring({}, NULL)
# CRASHES dict_popstring({"a": 1}, NULL)

def test_dict_as_frozendict_and_clear(self):
# Test PyDict_AsFrozenDictAndClear()
as_frozendict = _testcapi.dict_as_frozendict_and_clear
d = {1: 2, 'a': 'b'}
f = as_frozendict(d)
self.assertIs(type(f), frozendict)
self.assertEqual(f, frozendict({1: 2, 'a': 'b'}))
self.assertIs(type(d), dict)
self.assertEqual(d, {})

d = {}
f = as_frozendict(d)
self.assertIs(type(f), frozendict)
self.assertEqual(f, frozendict())
self.assertIs(type(d), dict)
self.assertEqual(d, {})

class DictSubtype(dict): ...
Comment thread
sobolevn marked this conversation as resolved.

d = DictSubtype({'x': None})
f = as_frozendict(d)
self.assertIs(type(f), frozendict)
self.assertEqual(f, frozendict({'x': None}))
self.assertIs(type(d), DictSubtype)
self.assertEqual(d, DictSubtype({}))

for wrong_input in (frozendict(), [], None):
with self.subTest(wrong_input=wrong_input):
with self.assertRaises(SystemError):
Comment thread
sobolevn marked this conversation as resolved.
as_frozendict(wrong_input)

def test_frozendict_check(self):
# Test PyFrozenDict_Check()
check = _testcapi.frozendict_check
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Add :c:func:`PyDict_AsFrozenDictAndClear` C-API function to create
:class:`frozendict` from existing :class:`dict` object and clear the input
dict instance.
8 changes: 8 additions & 0 deletions Modules/_testcapi/dict.c
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ test_dict_iteration(PyObject* self, PyObject *Py_UNUSED(ignored))
Py_RETURN_NONE;
}

static PyObject *
dict_as_frozendict_and_clear(PyObject *self, PyObject *obj)
{
NULLABLE(obj);
return PyDict_AsFrozenDictAndClear(obj);
}


static PyObject *
frozendict_check(PyObject *self, PyObject *obj)
Expand Down Expand Up @@ -306,6 +313,7 @@ static PyMethodDef test_methods[] = {
{"dict_popstring", dict_popstring, METH_VARARGS},
{"dict_popstring_null", dict_popstring_null, METH_VARARGS},
{"test_dict_iteration", test_dict_iteration, METH_NOARGS},
{"dict_as_frozendict_and_clear", dict_as_frozendict_and_clear, METH_O},
{"frozendict_check", frozendict_check, METH_O},
{"frozendict_checkexact", frozendict_checkexact, METH_O},
{"anydict_check", anydict_check, METH_O},
Expand Down
67 changes: 63 additions & 4 deletions Objects/dictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3120,6 +3120,17 @@ clear_embedded_values(PyDictValues *values, Py_ssize_t nentries)
}
}

// This function is used in both `PyDict_Clear`
// and `PyDict_AsFrozenDictAndClear`, place all the common parts here.
static void
clear_common(PyDictObject *mp)
{
_PyDict_NotifyEvent(PyDict_EVENT_CLEARED, mp, NULL, NULL);
// We don't inc ref empty keys because they're immortal
ensure_shared_on_resize(mp);
STORE_USED(mp, 0);
}

static void
clear_lock_held(PyObject *op)
{
Expand All @@ -3139,10 +3150,7 @@ clear_lock_held(PyObject *op)
return;
}
/* Empty the dict... */
_PyDict_NotifyEvent(PyDict_EVENT_CLEARED, mp, NULL, NULL);
// We don't inc ref empty keys because they're immortal
ensure_shared_on_resize(mp);
STORE_USED(mp, 0);
clear_common(mp);
if (oldvalues == NULL) {
set_keys(mp, Py_EMPTY_KEYS);
assert(oldkeys->dk_refcnt == 1);
Expand Down Expand Up @@ -8521,6 +8529,57 @@ frozendict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return d;
}

static void
transfer_keys_and_values_lock_held(PyObject *res, PyObject *dict)
{
PyDictObject *new = (PyDictObject *)res;
Comment thread
sobolevn marked this conversation as resolved.
PyDictObject *old = (PyDictObject *)dict;
assert(can_modify_dict(old));

// Fast path: do nothing on an empty dict:
if (old->ma_keys == Py_EMPTY_KEYS) {
return;
}

Py_ssize_t used = old->ma_used;
PyDictKeysObject *keys = old->ma_keys;
PyDictValues *values = old->ma_values;

// Clear the old dict keys and values, but do not decref them:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

By the way, the existing similar (but private) _PyList_AsTupleAndClear() has a similar design: first make the list empty, and then create a tuple from the list items.

clear_common(old);
set_keys(old, Py_EMPTY_KEYS);
set_values(old, NULL);
ASSERT_CONSISTENT(old);

// Transfer keys and values from dict to frozendict:
new->ma_used = used;
new->ma_keys = keys;
new->ma_values = values;
ASSERT_CONSISTENT(new);
}

PyObject *
PyDict_AsFrozenDictAndClear(PyObject *dict)
{
if (dict == NULL || !PyDict_Check(dict)) {
PyErr_BadInternalCall();
return NULL;
}

PyObject *res = frozendict_new_untracked(&PyFrozenDict_Type);
if (res == NULL) {
return NULL;
}

Py_BEGIN_CRITICAL_SECTION(dict);
transfer_keys_and_values_lock_held(res, dict);
Py_END_CRITICAL_SECTION();

_PyObject_GC_TRACK(res);
assert(_PyFrozenDictObject_CAST(res)->ma_hash == -1);
return res;
}


PyObject*
PyFrozenDict_New(PyObject *iterable)
Expand Down
2 changes: 1 addition & 1 deletion Python/marshal.c
Original file line number Diff line number Diff line change
Expand Up @@ -1501,7 +1501,7 @@ r_object(RFILE *p)
Py_CLEAR(v);
}
if (type == TYPE_FROZENDICT && v != NULL) {
Py_SETREF(v, PyFrozenDict_New(v));
Py_SETREF(v, PyDict_AsFrozenDictAndClear(v));
}
retval = v;
break;
Expand Down
Loading