python / python/cpython

`sys.getsizeof()` does not include inline values

Open
#128,762 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

interpreter-core type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

Commit tested: 5e65a1acc0b

I have a program that allocates numerous instances of this type:

@dataclass
class Node:
    cdr: Self | None

BIG_DATA = None
for i in range(50):
    BIG_DATA = Node(BIG_DATA)
    print(sys.getsizeof(BIG_DATA))

After the 28th iteration, I find that it stabilizes at printing 48. But if I run the program in GDB and trace the actual allocations, I see that it is allocating 80 bytes per iteration:

# Set a GDB-recognized breakpoint
os.kill(os.getpid(), signal.SIGTRAP)
# In GDB:
# b _PyObject_Malloc
# commands
#  silent
#  print nbytes
#  continue
# end
for i in range(50):
    BIG_DATA = Node(BIG_DATA)

I believe that the missing bytes can be accounted for in the inline values. I observe the same behavior on Python 3.13.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Linked PRs
  • gh-128763

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reported sys.getsizeof() behavior and reproduce the dataclass Node example while comparing its output with the _PyObject_Malloc trace in GDB. Investigate how inline values are accounted for; done means the reported size reflects the allocations demonstrated by the example without regressing existing behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.