Skip to content

dict.update() mutation check too broad #132617

Closed

Description

@colesbury

Bug report

The dict.update() modification check can be erroneously triggered by modifications to different dictionaries that happen to share the underlying keys objects.

For example, in the following program, the creation and modification of the f2 object can lead to an incorrect RuntimeError raised in the main thread that operates on distinct dictionaries.

import time
import threading

b = threading.Barrier(2)

class Foo:
    pass

class MyStr(str):
    def __hash__(self):
        return super().__hash__()

    def __eq__(self, other):
        time.sleep(0.1)
        return super().__eq__(other)


def thread():
    b.wait()
    time.sleep(0.05)

    f2 = Foo()
    f2.a = "a"
    f2.b = "b"
    f2.c = "c"

def main():
    t1 = threading.Thread(target=thread)
    t1.start()

    b.wait()

    f1 = Foo()
    f1.a = "a"
    f1.b = "b"

    x = {}
    x[MyStr("a")] = MyStr("a")
    x.update(f1.__dict__)

    t1.join()

if __name__ == "__main__":
    main()
Traceback (most recent call last):
  File "/home/sgross/cpython/bad.py", line 44, in <module>
    main()
    ~~~~^^
  File "/home/sgross/cpython/bad.py", line 39, in main
    x.update(f1.__dict__)
    ~~~~~~~~^^^^^^^^^^^^^
RuntimeError: dict mutated during update

Linked PRs

Activity

  1. added
    3.13only security fixes
    3.14bugs and security fixes
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    type-bugAn unexpected behavior, bug, or error
    on Apr 16, 2025
  2. added a commit that references this issue on May 27, 2025
  3. added a commit that references this issue on Jun 16, 2025
  4. added a commit that references this issue on Jun 16, 2025
  5. added 3 commits that reference this issue on Jun 16, 2025
  6. added a commit that references this issue on Jun 19, 2025
  7. added a commit that references this issue on Jul 12, 2025
  8. added a commit that references this issue on Aug 4, 2025
  9. added a commit that references this issue on Aug 19, 2025
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

    3.13only security fixes3.14bugs and security fixesinterpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions