Skip to content

Commit

Permalink
Use PyType_GetDict to safely access tp_dict [3.12]
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p authored and ijl committed Aug 3, 2023
1 parent e9b745e commit 5c8f93d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,20 @@ macro_rules! str_hash {
};
}

#[cfg(Py_3_10)]
#[cfg(Py_3_12)]
macro_rules! pydict_contains {
($obj1:expr, $obj2:expr) => {
unsafe {
pyo3_ffi::_PyDict_Contains_KnownHash(
pyo3_ffi::PyType_GetDict($obj1),
$obj2,
(*$obj2.cast::<pyo3_ffi::PyASCIIObject>()).hash,
) == 1
}
};
}

#[cfg(all(Py_3_10, not(Py_3_12)))]
macro_rules! pydict_contains {
($obj1:expr, $obj2:expr) => {
unsafe {
Expand Down
12 changes: 12 additions & 0 deletions test/test_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,15 @@ def default(obj):
orjson.dumps(ref, default=default)

assert sys.getrefcount(ref) == 2 # one for ref, one for default

def test_default_set(self):
"""
dumps() default function with set
"""

def default(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError

assert orjson.dumps({1, 2}, default=default) == b"[1,2]"

0 comments on commit 5c8f93d

Please sign in to comment.