Skip to content

A slotted class can be referenced weakly - #336

Merged
Paebbels merged 5 commits into
devfrom
claude/weakref-in-slotted-types
Sep 26, 2026
Merged

Paebbels merged 5 commits into
devfrom
claude/weakref-in-slotted-types

Conversation

@pytooling-claude

@pytooling-claude pytooling-claude Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

New Features

  • A slotted class can be referenced weakly, with the new weakref class keyword argument — closes
    #49.

    class Slotted(metaclass=ExtendedType, slots=True):
      _field: int
    
    weakref.ref(Slotted())     # TypeError: cannot create weak reference to 'Slotted' object

    A class using __slots__ has no __dict__ for weakref to keep its bookkeeping in, and the slot that would
    hold it is not created unless it is asked for:

    class Node(metaclass=ExtendedType, slots=True, weakref=True):
      _parent: "Node"
    
    reference = ref(Node())    # fine

    The typical reason to want it is a back-reference — a child pointing at its parent keeps the parent alive as
    long as the child lives, and a weak reference is how that cycle is avoided.

  • __weakref__ is requested like any other slot. weakref=True adds it to the fields the annotations
    declare, so the existing duplicate check handles it: a derived class inherits the capability, and asking again
    is an AttributeError, like any other duplicate slot:

    class Base(metaclass=ExtendedType, slots=True, weakref=True): ...
    class Derived(Base): ...                   # already weak-referenceable
    class Again(Base, weakref=True): ...       # AttributeError: slot '__weakref__' already exists
  • A mixin-class can ask for it too. __weakref__ becomes one of its mixin slots and is added to the class it
    is mixed into. If that class has it already, Python rejects the second one with
    TypeError: __weakref__ slot disallowed.

  • __weakref__ and __dict__ can't be annotated. Both raise an ExtendedTypeError, whose note points to the
    intended spelling: weakref=True for __weakref__, slots=False for __dict__. Annotating __dict__ in a
    slotted class used to work silently, and it gave up what slots save.

Changes

  • ExtendedType's .. todo:: on __dict__ and __weakref__ is removed: __weakref__ is weakref=True, and
    __dict__ in a slotted class is rejected.
  • weakref is ordered after mixin and before singleton.

Documentation

  • doc/MetaClasses.rst — a new Weak References section: why a slotted class is not weak-referenceable, the
    example, the once-per-hierarchy rule, mixin-classes, the rejected annotations, and the note that a class without
    slots already is.

Unit Tests

  • tests/unit/MetaClasses/WeakReferences.py — 17 testcases:
    • WeakReferences (12): a slotted class is not weak-referenceable by default, the keyword adds the slot, an
      instance can be referenced, the reference dies with the object, the data fields still work, a derived class
      inherits it without repeating it, asking twice is an error, a mixin's fields are unaffected, a mixin-class
      contributes it and passes it through a mixin-class of mixin-classes, and asking in a mixin-class for a class
      that has it already is an error.
    • AnnotatedWeakref (3), AnnotatedDict (2): the annotation is rejected in a slotted class, a mixin-class and,
      for __weakref__, an unslotted class.
  • 2474 passed, 30 skipped, 3 xfailed, 773 subtests. Every local check at its baseline.

Related Issues and Pull-Requests

  • Closes #49 — "Add support for __weakref__ in types with
    slots"
    , open since 2022-05-14. Its other half, __dict__ in slotted types, was struck out in the description
    and is not addressed here.

@pytooling-claude
pytooling-claude Bot requested a review from Paebbels as a code owner August 25, 2026 00:15
@codacy-production

codacy-production Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 7 minor

Alerts:
⚠ 7 issues (≤ 0 issues of at least minor severity)

Results:
7 new issues

Category Results
UnusedCode 6 minor
Documentation 1 minor

View in Codacy

🟢 Metrics 22 complexity · 0 duplication

Metric Results
Complexity 22
Duplication 0

View in Codacy

🟢 Coverage 100.00% diff coverage · +0.02% coverage variation

Metric Results
Coverage variation ✅ +0.02% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (6939868) 15514 13442 86.64%
Head commit (af6d1f1) 15528 (+14) 13458 (+16) 86.67% (+0.02%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#336) 16 16 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@codecov

codecov Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

❌ 2 Tests Failed:

Tests completed Failed Passed Skipped
2490 2 2488 17
View the top 2 failed test(s) by shortest run time
WeakReferences.WeakReferences::test_AMixinContributesIt
Stack Traces | 0.001s run time
No failure message available
WeakReferences.WeakReferences::test_AMixinOfMixinsKeepsIt
Stack Traces | 0.002s run time
No failure message available

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

@Paebbels
Paebbels force-pushed the claude/weakref-in-slotted-types branch from d1c222f to a5cc534 Compare August 25, 2026 07:05
@pytooling-claude

Copy link
Copy Markdown
Author

🪲 This was red on all four PyPy 3.11 jobs, and the tests were wrong, not the feature. Fixed and pushed.

FAILED tests/unit/MetaClasses/WeakReferences.py::WeakReferences::test_ASlottedClassIsNotWeakReferenceableByDefault
       - AssertionError: TypeError not raised
FAILED tests/unit/MetaClasses/WeakReferences.py::WeakReferences::test_TheReferenceDiesWithTheObject
       - AssertionError: <...Slotted object at 0x1ba4f868> is not None

Both encoded CPython behaviour rather than the feature's:

  • On PyPy every object is weak-referenceable, slots or not — there is no __weakref__ slot to be missing. So "a slotted class is not weak-referenceable by default" is simply false there. The testcase is split: the slot is absent on every implementation, and the TypeError that follows from its absence is asserted on CPython only, with @mark.skipif(CurrentPlatform.IsPyPy, ...).
  • PyPy does not count references. It collects generationally, so del instance leaves the object alive and the weak reference still resolves. One gc.collect() makes the testcase portable — and it is the honest assertion anyway, since "dies with the object" means "dies when collected".

The feature itself needed no change: test_WeakrefAddsTheSlot passed on PyPy all along, so the slot is added there too. The documentation now says the restriction being lifted is CPython's, and that on PyPy the keyword adds the slot but changes nothing observable — code targeting both keeps it, because it is what makes the class work on CPython.

Worth noting for the release: PyPy is the only place this difference shows, and it took CI to find it — this container has no PyPy interpreter.

@pytooling-claude pytooling-claude Bot mentioned this pull request Aug 25, 2026
@Paebbels
Paebbels force-pushed the claude/weakref-in-slotted-types branch 6 times, most recently from 6beb632 to cf1f113 Compare September 6, 2026 01:27
@Paebbels Paebbels linked an issue Sep 6, 2026 that may be closed by this pull request
@pytooling-claude pytooling-claude Bot added this to the v10.0 milestone Sep 6, 2026
@Paebbels
Paebbels force-pushed the claude/weakref-in-slotted-types branch from cf1f113 to 5ce4fc1 Compare September 6, 2026 23:56
@Paebbels
Paebbels force-pushed the claude/weakref-in-slotted-types branch 2 times, most recently from 2482203 to bb51986 Compare September 8, 2026 21:40
@Paebbels
Paebbels force-pushed the claude/weakref-in-slotted-types branch from bb51986 to bfa65b5 Compare September 23, 2026 20:58
claude-code and others added 2 commits September 25, 2026 22:23
Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
Two of them encoded CPython's behaviour rather than the feature's, and failed on all four
PyPy 3.11 jobs:

* 'A slotted class is not weak-referenceable by default' is false on PyPy - every object there
  is weak-referenceable, slots or not. Split in two: the slot is absent everywhere, and the
  TypeError that follows from it is asserted on CPython only.
* 'The reference dies with the object' assumed reference counting. PyPy collects
  generationally, so 'del' alone leaves the object alive; 'gc.collect()' makes it portable.

The documentation now says the restriction being lifted is CPython's, so the keyword reads as
what it is on PyPy: harmless, and still required for the CPython case.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
@Paebbels
Paebbels force-pushed the claude/weakref-in-slotted-types branch from bfa65b5 to 0e5d49b Compare September 25, 2026 22:28
…an't be annotated

* 'weakref=True' on a mixin-class adds '__weakref__' to its mixin slots. The class it's mixed into lists it once,
  and not at all if a base-class already provides it.
* Annotating '__weakref__' raises an ExtendedTypeError, with a note pointing to 'weakref=True'.
* Annotating '__dict__' raises an ExtendedTypeError, with a note pointing to 'slots=False'.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
Comment thread pyTooling/MetaClasses/__init__.py Resolved
* 'weakref=True' adds '__weakref__' to the fields the annotations declare, so the existing duplicate check and the
  mixin-slot aggregation handle it. The loops over base-classes and the special cases for mixin-classes are gone.
* Asking again in a derived class is an AttributeError now, like any other duplicate slot. A mixin-class asking for
  it on a class that has it already fails with Python's TypeError.
* 'weakref' is ordered after 'mixin' and before 'singleton', and '_computeSlots' has no default for it.
* The '__dict__' todo is solved: annotating '__dict__' is rejected.

Co-Authored-By: Patrick Lehmann <Paebbels@gmail.com>
Comment thread pyTooling/MetaClasses/__init__.py Resolved
@Paebbels
Paebbels merged commit 5f68c39 into dev Sep 26, 2026
5 of 6 checks passed
@Paebbels
Paebbels deleted the claude/weakref-in-slotted-types branch September 26, 2026 08:35
This was referenced Oct 12, 2026
This was referenced Oct 20, 2026
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.

Add support for __weakref__ in types with slots

2 participants