Skip to content

WeakKeyDictionary doesn't accept some subclassed builtins as keys #149895

@w-mcilhagga

Description

@w-mcilhagga

Bug report

Bug description:

the current documentation on weak references says that to use a dict as a weak key, you should subclass it. However, this doesn't work.

here's a copy of a cmd-line session (running on Windows 11):

C:/path/to/dir>py
Python 3.14.5 (tags/v3.14.5:5607950, May 10 2026, 10:43:50) [MSC v.1944 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import weakref
>>> d = weakref.WeakKeyDictionary()
>>> class Dict(dict):
...     pass
...
>>> obj = Dict(red=1, green=2, blue=3)
>>> d[obj] = 1
Traceback (most recent call last):
  File "<python-input-4>", line 1, in <module>
    d[obj] = 1
    ~^^^^^
  File "C:\Users\willi\AppData\Local\Python\pythoncore-3.14-64\Lib\weakref.py", line 335, in __setitem__
    self.data[ref(key, self._remove)] = value
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'weakref.ReferenceType' as a dict key (unhashable type: 'Dict')

The documentation explicitly says that the Dict type in this example can be used as a key (and I copied the Dict declaration and instantiation line from the documentation)

However, the following (from the documentation) does work:

class Str(str):
    pass

obj = Str()
d[obj] = 1

In passing, it doesn't accept subclassed lists or numpy arrays as keys either.

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions