Skip to content

functools.cmp_to_key should keep strong reference during call #162856

Backlog

Description

@cmaloney

Bug report

Currently functools.cmp_to_key keeps a reference to the object currently being called only via its members. Those members can be set by the arbitrary python running in the compare though which can clear the reference. This leads to segfaults because the object is still in use.

import functools
import operator

class L(list):
    pass
class Evil:
    def __eq__(evil, other):
        k.obj = None
        return True
K = functools.cmp_to_key(operator.eq)
k = K(L([Evil(), 1, 2, 3]))   # Evil.__eq__ does k.obj = None
k < K([1, 1, 2, 3])

found in https://github.com/python/cpython/pull/162369/changes#r4736399316

CPython versions tested on:

3.14, 3.15, CPython main branch

Operating systems tested on:

No response

Activity

  1. self-assigned this
    on Nov 30, 2026
  2. added
    type-bug
    3.14
    3.15
    3.16
    on Nov 30, 2026
  3. added
    interpreter-core
    on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

3.143.153.16interpreter-coretype-bug

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions