Overcoming Python's limitations regarding instance methods

copy, instance-method, oop, python

Solution

You might be able to do this using `copy_reg.pickle`. In Python 2.6:

import copy_reg
import types

def reduce_method(m):
    return (getattr, (m.__self__, m.__func__.__name__))

copy_reg.pickle(types.MethodType, reduce_method)

This does not store the code of the method, just its name; but that will work correctly in the common case.

This makes both pickling and copying work!

Problem

It seems that Python has some limitations regarding instance methods. - Instance methods can't be copied. - Instance methods can't be pickled. This is problematic for me, because I work on a very object-oriented project in which I reference instance methods, and there's use of both deepcopying and pickling. The pickling thing is done mostly by the multiprocessing mechanism. What would be a good way to solve this? I did some ugly workaround to the copying issue, but I'm looking for a nicer solution to both problems. Does anyone have any suggestions? Update: My use case: I have a tiny event system. Each event has an `.action` attribute that points to a function it's supposed to trigger, and sometimes that function is an instance method of some object.

Original source