Skip to content

add logic to convert dict list key to tuple #633

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions msgpack/fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,8 @@ def _unpack(self, execute=EX_CONSTRUCT):
raise ValueError("%s is not allowed for map key" % str(type(key)))
if isinstance(key, str):
key = sys.intern(key)
if isinstance(key, list):
key = tuple(key)
Comment on lines +532 to +533
Copy link
Contributor

Choose a reason for hiding this comment

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

Is tuple the only data type that is valid as a dict key and that would come back as a list after pack/unpack?

Nitpick: use elif

ret[key] = self._unpack(EX_CONSTRUCT)
if self._object_hook is not None:
ret = self._object_hook(ret)
Expand Down
19 changes: 19 additions & 0 deletions msgpack/unpack.h
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,25 @@ static inline int unpack_callback_map_item(unpack_user* u, unsigned int current,
if (PyUnicode_CheckExact(k)) {
PyUnicode_InternInPlace(&k);
}
if (PyList_CheckExact(k)) {
Copy link
Contributor

Choose a reason for hiding this comment

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

nitpick: use else if

Py_ssize_t list_size = PyList_Size(k);
PyObject* tuple = PyTuple_New(list_size);

if (tuple == NULL) {
return -1;
}

for (Py_ssize_t i = 0; i < list_size; i++) {
PyObject* item = PyList_GetItem(k, i);
Py_INCREF(item);
if (PyTuple_SetItem(tuple, i, item) != 0) {
Py_DECREF(tuple);
return -1;
}
}
Py_DECREF(k);
k = tuple;
}
if (u->has_pairs_hook) {
msgpack_unpack_object item = PyTuple_Pack(2, k, v);
if (!item)
Expand Down
4 changes: 4 additions & 0 deletions test/test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,7 @@ def test_match():

def test_unicode():
assert unpackb(packb("foobar"), use_list=1) == "foobar"


def test_dict_tuple_key():
unpackb(packb({(1, 2): 3}), strict_map_key=False)
Loading