Skip to content
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

Default to str() for Unknown objects as keys when using OPT_NON_STR_KEYS #454

Closed
wants to merge 1 commit into from
Closed
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
14 changes: 12 additions & 2 deletions src/serialize/per_type/dict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,14 +346,24 @@ impl DictNonStrKey {
Ok(CompactString::from(uni.unwrap()))
}
}
ObType::Unknown => {
let key_str_obj = ffi!(PyObject_Str(key));
debug_assert!(ffi!(Py_REFCNT(key_str_obj)) >= 2);
if unlikely!(key_str_obj.is_null()) {
Err(SerializeError::DictKeyInvalidType)
} else {
let ret = Self::pyobject_to_string(key_str_obj, opts);
ffi!(Py_DECREF(key_str_obj));
ret
}
}
ObType::Tuple
| ObType::NumpyScalar
| ObType::NumpyArray
| ObType::Dict
| ObType::List
| ObType::Dataclass
| ObType::Fragment
| ObType::Unknown => Err(SerializeError::DictKeyInvalidType),
| ObType::Fragment => Err(SerializeError::DictKeyInvalidType),
}
}
}
Expand Down
18 changes: 5 additions & 13 deletions test/test_non_str_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,13 +244,6 @@ def test_dict_keys_str(self):
orjson.dumps({"1": True}, option=orjson.OPT_NON_STR_KEYS) == b'{"1":true}'
)

def test_dict_keys_type(self):
class Obj:
a: str

val = Obj()
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS)

@pytest.mark.skipif(numpy is None, reason="numpy is not installed")
def test_dict_keys_array(self):
Expand Down Expand Up @@ -290,17 +283,16 @@ def test_dict_keys_tuple(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(obj, option=orjson.OPT_NON_STR_KEYS)

def test_dict_keys_unknown(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps({frozenset(): True}, option=orjson.OPT_NON_STR_KEYS)

def test_dict_keys_no_str_call(self):
def test_dict_keys_str_call(self):
class Obj:
a: str

def __str__(self):
return "Obj"

val = Obj()
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS)
assert (
orjson.dumps({val: True}, option=orjson.OPT_NON_STR_KEYS) == b'{"Obj":true}'
)