python-attrs / python-attrs/attrs

Reference cycle for slot classes

Open
#1,047 13 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.8k
Forks
480
Avg merge
2h 15m
Merged PRs (30d)
2

Description

Even the birds on the branches nowadays know we do a class switcheroo when defining slot classes.

The initial class (the one we throw away) is part of a reference cycle with something else, so it doesn't get GC'd right away. A tiny example:

from attrs import define


@define
class A:
    a: int


@define
class B(A):
    b: int


# collect()
print(A.__subclasses__())  # [<class '__main__.B'>, <class '__main__.B'>]

If gc.collect() is called right afterwards, the old class gets cleaned up, so it's almost certainly a reference cycle.

So, a good issue for someone getting started with attrs: find out what the reference cycle is and break it so this doesn't happen.

Alternatively, we could call gc.collect() ourselves. We could also check for the old class in __subclasses__() and emit a warning if we find it there; it probably means someone is using a bare super somewhere we didn't rewrite it.

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 by reproducing the attrs class-switching example from the issue and inspect the references that keep the initial slot class alive. Use gc.collect() and A.subclasses() to confirm the cycle and compare behavior before and after class creation. Done means the discarded class is no longer retained without requiring an explicit collection.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.