Skip to content

Commit 0d3fce6

Browse files
Use PyFrozenDict_Check and PyFrozenDict_CheckExact
Found out these exist while reading through https://vstinner.github.io/pep-814-add-frozendict-builtin-type.html. https://github.com/python/cpython/blob/39a9a47516abf8a68cb3239f968c2b2135c3a5a7/Include/cpython/dictobject.h#L35-L43 Signed-off-by: Edgar Ramírez Mondragón <edgarrm358@gmail.com>
1 parent 31508e2 commit 0d3fce6

2 files changed

Lines changed: 22 additions & 14 deletions

File tree

msgpack/_packer.pyx

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import sys
2-
31
from cpython cimport *
42
from cpython.bytearray cimport PyByteArray_Check, PyByteArray_CheckExact
53
from cpython.datetime cimport (
@@ -12,21 +10,16 @@ cdef Timestamp
1210

1311
from .ext import ExtType, Timestamp
1412

15-
# frozendict is a builtin type added in Python 3.15 (PEP 814).
16-
if sys.version_info >= (3, 15):
17-
import builtins
18-
19-
frozendict = builtins.frozendict
20-
else:
21-
22-
class frozendict:
23-
pass
24-
2513

2614
cdef extern from "Python.h":
2715

2816
int PyMemoryView_Check(object obj)
2917

18+
cdef extern from "frozendict_compat.h":
19+
20+
bint PyFrozenDict_Check(object obj)
21+
bint PyFrozenDict_CheckExact(object obj)
22+
3023
cdef extern from "pack.h":
3124
struct msgpack_packer:
3225
char* buf
@@ -214,8 +207,8 @@ cdef class Packer:
214207
rawval = o
215208
msgpack_pack_raw(&self.pk, L)
216209
msgpack_pack_raw_body(&self.pk, rawval, L)
217-
elif (PyDict_CheckExact(o) or type(o) is frozendict) if strict \
218-
else (PyDict_Check(o) or isinstance(o, frozendict)):
210+
elif (PyDict_CheckExact(o) or PyFrozenDict_CheckExact(o)) if strict \
211+
else (PyDict_Check(o) or PyFrozenDict_Check(o)):
219212
L = len(o)
220213
if L > ITEM_LIMIT:
221214
raise ValueError("dict is too large")

msgpack/frozendict_compat.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#ifndef MSGPACK_FROZENDICT_COMPAT_H
2+
#define MSGPACK_FROZENDICT_COMPAT_H
3+
4+
#include <Python.h>
5+
6+
/* frozendict (PEP 814) is a builtin type added in CPython 3.15. */
7+
#if PY_VERSION_HEX >= 0x030f0000
8+
/* PyFrozenDict_Check / PyFrozenDict_CheckExact come from
9+
* Include/cpython/dictobject.h, pulled in transitively by Python.h. */
10+
#else
11+
#define PyFrozenDict_Check(op) 0
12+
#define PyFrozenDict_CheckExact(op) 0
13+
#endif
14+
15+
#endif

0 commit comments

Comments
 (0)