python / python/cpython

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

Open
#93,889 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
36k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the MWE with pickle.dumps and pickle.loads, focusing on the bound method assigned to Foo.f2 and the reported getattr(type(im_self), funcname) failure. Trace the method round-trip behavior and existing pickle handling; done means the example unpickles successfully and prints [[1.]].

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.