2

In Python, it's usually easy to monkey-patch a method of an object:

import types

class MyClass:
    def foo(self):
        print("hi")

obj = MyClass()
obj.foo()  # => hi

def myfoo(self):
    print("hello")

obj.foo = types.MethodType(myfoo, obj)
obj.foo()  # => hello

This behavior is not so simple for magic (__*__) methods, and I assume something similar to the linked question is happening when this fails:

import pickle, io

class MyClass:
    def __reduce__(self):
        return (MyClass, tuple())

buffer = io.BytesIO()
pickler = pickle.Pickler(buffer)

obj = MyClass()
pickler.dump(obj)

def myreduce(self):
    print("hello")
    return (MyClass, tuple())

obj.__reduce__ = types.MethodType(myreduce, obj)
pickler.dump(obj)

Where the above does not output hello.

Bizarely, the above does output hello if you change pickler.dump to pickle.dumps. Unfortunately, this is not actually a solution for me: I'm trying to customize the serialization of an object in PyTorch, whose torch.save uses a Pickler object.

Is it possible customize the pickling behavior of a single object?

Linuxios
  • 34,849
  • 13
  • 91
  • 116

0 Answers0