[Python-Dev] Pickling objects that return string from reduce (original) (raw)

Bruce Christensen t-bruch at microsoft.com
Mon Jul 17 22:14:36 CEST 2006


I'm still plugging away on IronPython's cPickle, and I've stumbled across another ambiguity in the pickle docs. From http://docs.python.org/lib/node69.html:

"If a string is returned, it names a global variable whose contents are pickled as normal. The string returned by reduce should be the object's local name relative to its module; the pickle module searches the module namespace to determine the object's module."

What exactly does that last clause mean? Must the object have a module attribute? What if it doesn't? What if the module exists but isn't currently imported?

Is something like the following close?

# Call copy_reg-registered func, obj.__reduce_ex__, or

obj.reduce result = call_reduce(obj)

if type(result) == tuple:
    ... (do appropriate things here)
elif isinstance(result, basestring):
    name = result
    module = "<unknown module>"
    try:
        module = obj.__module__
        found_obj = getattr(sys.modules[module], name)
    except AttributeError, KeyError:
        raise PicklingError(
            "Can't pickle %r: it's not found as %s.%s"
            % (obj, module, name)
            )

    if found_obj is not obj:
        raise PicklingError(
            "Can't pickle %r: it's not the same object as %s.%s"
            % (obj, module, name)
            )

    emit("c%s\n%s\n" % module, name)

Thanks,

--Bruce



More information about the Python-Dev mailing list