Skip to content

Conversation

@hyongtao-code
Copy link
Contributor

@hyongtao-code hyongtao-code commented Dec 20, 2025

Replace .copy() with list(...) to correctly create a shallow copy for any sequence type.

A regression test is added to cover this case.

Mini Reproducible Script:

import tracemalloc

tracemalloc.start(25)
snap = tracemalloc.take_snapshot()
snap2 = tracemalloc.Snapshot(tuple(snap.traces._traces), snap.traceback_limit)
snap2.filter_traces(())
print("done")

Result without patch

D:\MyCode\cpython\PCbuild\amd64>python_d.exe py_tracemalloc.py
Traceback (most recent call last):
  File "D:\MyCode\cpython\PCbuild\amd64\py_tracemalloc.py", line 6, in <module>
    snap2.filter_traces(())
    ~~~~~~~~~~~~~~~~~~~^^^^
  File "D:\MyCode\cpython\Lib\tracemalloc.py", line 474, in filter_traces
    new_traces = self.traces._traces.copy()
                 ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'copy'

Result with patch

D:\MyCode\cpython\PCbuild\amd64>python_d.exe py_tracemalloc.py
done

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 <[email protected]>
Copy link
Member

@sobolevn sobolevn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not quite that this change is correct. filters is documented to be a list: https://docs.python.org/3/library/tracemalloc.html#tracemalloc.Snapshot.filter_traces

But now, it will allow more types in, like str or set.
Which is goes against the docs?

@hyongtao-code
Copy link
Contributor Author

Thanks for pointing this out — you’re right : )

My confusion was about the tuple case and the copy() call, but an empty filters argument is effectively a no-op and doesn’t justify relaxing the API.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants