python / python/cpython

Can't pickle a bound method if `getattr(type(im_self), funcname)` fails

未关闭
#93,889 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib type-bug
主要语言
Python
星标
77.2k
派生
36k
平均合并
1 天 9 小时
30 天内合并 PR
558

描述

Bug report

MWE:

import pickle
import numpy as np
from scipy.interpolate import RectBivariateSpline

class Foo:
    def __init__(self):
        x = np.linspace(0,1,10)[:,None]
        y = np.linspace(2,3,9)[None,:]
        self.f = RectBivariateSpline(x,y,x*y)
        def f2(self,x,y):
            return self.f(x,y)
        self.f2 = f2.__get__(self)

foo = Foo()
pickled = pickle.dumps(foo)
unpickled = pickle.loads(pickled)

print(unpickled.f2(0.5, 0.6))

Expected output is to print [[1.]]. Actually gives an exception

Traceback (most recent call last):
  File ".../pickle-test.py", line 18, in <module>
    unpickled = pickle.loads(pickled)
AttributeError: 'Foo' object has no attribute 'f2'

This issue follows up from the identification an fixing of the same issue with dill, see
https://github.com/uqfoundation/dill/issues/510
https://github.com/uqfoundation/dill/pull/511
where @anivegesana commented

It seems to be a little bit more subtle than that. Because Python 3 implements its own reduce function for methods, I removed it from dill. It turns out that this is not a safe optimization in the case that the func is an inner function. Will be fixed soon.

Your environment

  • CPython versions tested on: 3.9.10
  • Operating system and architecture: Linux Mint 20.2 on x86-64

贡献指南

打开贡献指南

从这里开始

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

调研方向

首先使用 pickle.dumps 和 pickle.loads 重现 MWE,重点关注分配给 Foo.f2 的 bound method 以及报告的 getattr(type(im_self), funcname) 失败。跟踪该 method 的往返行为和现有的 pickle 处理;完成标准是示例能够成功 unpickle 并打印 [[1.]]。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
tooling
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
需要澄清
新手友好度
25/100

把新 issue 发到你的邮箱

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