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
14 changes: 14 additions & 0 deletions sentry_sdk/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
# Bytes are technically not strings in Python 3, but we can serialize them
serializable_str_types = (str, bytes, bytearray, memoryview)

# Exact built-in atomic types cannot hold references or form cycles, so
# cycle-detection memoization can be skipped for them.
_ATOMIC_TYPES = (str, int, float, bool, type(None))


# Maximum length of JSON-serialized event payloads that can be safely sent
# before the server may reject the event due to its size. This is not intended
Expand Down Expand Up @@ -199,6 +203,16 @@ def _serialize_node(
self.path.append(segment)

try:
if type(obj) in _ATOMIC_TYPES:
return self._serialize_node_impl(
obj,
is_databag=is_databag,
is_request_body=is_request_body,
should_repr_strings=should_repr_strings,
remaining_depth=remaining_depth,
remaining_breadth=remaining_breadth,
)

with self.memo.memoize(obj) as result:
if result:
return CYCLE_MARKER
Expand Down
53 changes: 53 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,56 @@ def __iter__(self):
assert result["custom"].startswith(
"<tests.test_serializer.test_serialize_local_vars.<locals>.Custom object at"
)


def test_atomic_values_skip_memo(monkeypatch):
from sentry_sdk.serializer import Memo

memoized_types = []
orig_memoize = Memo.memoize

def counting_memoize(self, obj):
memoized_types.append(type(obj))
return orig_memoize(self, obj)

monkeypatch.setattr(Memo, "memoize", counting_memoize)

class CustomStr(str):
def __sentry_repr__(self):
return "custom-str"

cyclic_list = []
cyclic_list.append(cyclic_list)

payload = {
"extra": {
"s": "hello",
"i": 42,
"f": 3.14,
"inf": float("inf"),
"b": True,
"n": None,
"sub": CustomStr("abc"),
"nested": [1, "two", None, {"k": False}],
"cycle": cyclic_list,
}
}

result = serialize(payload)

assert result["extra"]["s"] == "hello"
assert result["extra"]["i"] == 42
assert result["extra"]["f"] == 3.14
assert result["extra"]["inf"] == "inf"
assert result["extra"]["b"] is True
assert result["extra"]["n"] is None
assert result["extra"]["sub"] == "custom-str"
assert result["extra"]["nested"] == [1, "two", None, {"k": False}]
assert result["extra"]["cycle"] == ["<cyclic>"]

for atomic_type in (str, int, float, bool, type(None)):
assert atomic_type not in memoized_types

assert CustomStr in memoized_types
assert dict in memoized_types
assert list in memoized_types
Loading