Skip to content

Memory leak on dict pyclasses after setting dynamic attribute #5953

@threecgreen

Description

@threecgreen

Bug Description

I've created a repo with a single pyclass(dict) struct exported to Python. I see linear memory growth with tracemalloc after setattring a new dynamic field on each object. With the same object, if I don't create an attribute (and the dict is never created), the memory is freed as expected.

In clear_dict it looks like the dict is cleared but the ref count isn't decremented.

Steps to Reproduce

  1. git clone https://github.com/threecgreen/pyo3-dict-leak-repro
  2. cd pyo3-dict-leak-repro
  3. pip install maturin && maturin develop
  4. python test_leak.py

Backtrace

Without setattr:         1,140 bytes  (0.0 B/obj)
With setattr:       12,801,140 bytes  (64.0 B/obj)
Delta:              12,800,000 bytes
Expected: ~0 bytes leaked in both cases.
Actual:   ~64 bytes leaked per object when __dict__ is populated.

Your operating system and version

Linux

Your Python version (python --version)

3.10.10

Your Rust version (rustc --version)

1.94.0

Your PyO3 version

0.28.3

How did you install python? Did you use a virtualenv?

pyenv

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions