[Python-porting] Pickling unbound methods on Python 3

cool-RR cool-rr at cool-rr.com
Sun May 30 12:00:59 CEST 2010


On Sun, May 30, 2010 at 9:19 AM, "Martin v. Löwis" <martin at v.loewis.de>wrote:

> I can think of a few solutions:
>>
>> 1. Make `save_global` look in the classes inside the module as well.
>>
>
> How exactly would you do this? I don't think this is implementable,
> in a reasonable way.
>

I don't understand what the problem is with just looking in the classes
defined in the module:

"""
def find_containing_object_of_function(function):
    function_name = function.__name__
    module = sys.modules[function.__module__]
    objects_to_check = [module]
    while objects_to_check:
        object_to_check = objects_to_check.pop()
        if getattr(object_to_check, function_name, None) is function:
            return object_to_check
        try:
            sub_objects = vars(object_to_check)
        except TypeError: # The object doesn't have a vars/__dict__
            continue
        for sub_object in sub_objects.values():
            if isinstance(sub_object, type):
                objects_to_check.append(sub_object)

    raise LookupError('''Couldn't find the %s function for
pickling/deepcopying \
it. I tried looking around in the %s module, but it either wasn't there or \
was in a non-obvious place.''' % (function, module))


def reduce_function(function):
    containing_object = find_containing_object_of_function(function)
    return (getattr, (containing_object, function.__name__))
"""

This is not bulletproof, of course. But it'll work for most cases.


>  2. Allow me to specify a reducer for FunctionType.
>>
>
> How would the reducer work?
>
>
As above.

Ram.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-porting/attachments/20100530/72776186/attachment.html>


More information about the Python-porting mailing list