Skip to content

WeakSet &= and ^= leave dead references behind #162618

Backlog

Description

@paulboul1013

Bug report

Bug description

WeakSet.__iand__ (&=, intersection_update()) and WeakSet.__ixor__
(^=, symmetric_difference_update(), symmetric_difference()) can leave
dead weak references in the set's internal data. After that, len()
disagrees with iteration.

from collections import UserString
from weakref import WeakSet

# &= with an equal temporary
item = UserString('a')
ws = WeakSet([item])
ws &= map(UserString, 'a')
print(len(ws), list(ws), item in ws)

# &= with the same object, which then dies
item = UserString('a')
ws = WeakSet([item])
ws &= [item]
del item
print(len(ws), list(ws))

# ^= with a temporary
item = UserString('a')
ws = WeakSet([item])
ws ^= map(UserString, 'b')
print(len(ws), list(ws))

Output:

1 [] False
1 []
2 ['a']

In each case len() counts a dead reference. The second and third cases
should print 0 [] and 1 ['a'].

The first case depends on which equal item &= keeps. With a list,
set.intersection_update() keeps the one from other (with a set, it
depends on which set is smaller). For a WeakSet that is the temporary, so
the result would be 0 [] False. Keeping the set's own live item would
give 1 ['a'] True. Which one is intended?

__iand__ passes new ref(item) objects, without the removal callback, to
set.intersection_update(), which keeps those instead of the set's own refs.
In __ixor__, a temporary item can die before its ref is added to data,
so its removal callback runs too early and the dead ref stays.

This is similar to gh-162523 (WeakSet.isdisjoint() with temporaries).

CPython versions tested on

3.12, CPython main branch

Operating systems tested on

Linux

Duplicate search

Searched: "WeakSet intersection_update", "WeakSet symmetric_difference",
"WeakSet dead reference", "WeakSet len". Related: gh-58367 (closed 2012,
about __len__ during iteration, a different problem).

Linked PRs

Activity

  1. added
    type-bug
    on Nov 25, 2026
  2. added
    stdlib
    on Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions