python / python/cpython

Comment for bounded_lru_cache_wrapper seems incorrect

未关闭
#94,879 8 条评论 0 个 reaction 已指派 3 人 在 GitHub 查看

@tim-one 已经在做这个了。

开始于 2022年7月17日。

extension-modules type-bug
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

https://github.com/python/cpython/blob/c22f134211743cd5ad14cec1dd4f527bee542b4c/Modules/_functoolsmodule.c#L975-L976
However the __eq__ method call actually could be made for the deletion of the oldest entry.

from functools import lru_cache

class A:
    def __init__(self, name):
        self.name = name
        self.counter = []

    def __hash__(self):
        return 0 # mock hash collision
    
    def __eq__(self, __o: 'A'):
        self.counter.append(__o.name)
        return self is __o

@lru_cache(maxsize=2)
def foo(_):
    return 0

a, b, c = A('a'), A('b'), A('c')

foo(a)
foo(b)

# make 'b' be the oldest-used entry
# but not the oldest-inserted entry
foo(a)
a.counter.clear()

foo(c) # will evict 'b'

# The assertion shows that
# 'a' was compared with 'b' for the deletion of 'b'
assert 'b' in a.counter
print(a.counter) # ['c', 'c', 'b', 'c']

It seems that reentrant here might cause the assertion in L1092 failed:
https://github.com/python/cpython/blob/c22f134211743cd5ad14cec1dd4f527bee542b4c/Modules/_functoolsmodule.c#L1092-L1099
Since link has been extracted but hasn't been popped from cache dict, link list could be empty while cache dict is full.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。