From 97ccc3f2de3291732d3ce395bbb5021adfdc6a37 Mon Sep 17 00:00:00 2001 From: Yongtao Huang Date: Sat, 20 Dec 2025 16:10:42 +0800 Subject: [PATCH] Fix tracemalloc.Snapshot.filter_traces() for tuple traces storage Snapshot.filter_traces() assumed the internal traces container supports .copy(), which fails if a Snapshot is constructed with tuple traces. Fix: use list(self.traces._traces) in the no-filter branch to make a shallow copy without depending on the container type. Add a regression test that constructs a Snapshot with tuple storage and verifies filter_traces(()) works. Signed-off-by: Yongtao Huang --- Lib/test/test_tracemalloc.py | 7 +++++++ Lib/tracemalloc.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_tracemalloc.py b/Lib/test/test_tracemalloc.py index 9d3ff8a620b6f2..c9137f91215d31 100644 --- a/Lib/test/test_tracemalloc.py +++ b/Lib/test/test_tracemalloc.py @@ -446,6 +446,13 @@ def test_filter_traces(self): self.assertRaises(TypeError, snapshot.filter_traces, filter1) + def test_filter_traces_no_filter_tuple_storage(self): + snapshot, _snapshot2 = create_snapshots() + snap = tracemalloc.Snapshot(tuple(snapshot.traces._traces), + snapshot.traceback_limit) + snap2 = snap.filter_traces(()) + self.assertEqual(snap2.traces._traces, list(snap.traces._traces)) + def test_filter_traces_domain(self): snapshot, snapshot2 = create_snapshots() filter1 = tracemalloc.Filter(False, "a.py", domain=1) diff --git a/Lib/tracemalloc.py b/Lib/tracemalloc.py index cec99c59700fe0..65cc699a895ee1 100644 --- a/Lib/tracemalloc.py +++ b/Lib/tracemalloc.py @@ -471,7 +471,7 @@ def filter_traces(self, filters): exclude_filters, trace)] else: - new_traces = self.traces._traces.copy() + new_traces = list(self.traces._traces) return Snapshot(new_traces, self.traceback_limit) def _group_by(self, key_type, cumulative):