[Python-Dev] Pickling objects that return string from reduce
"Martin v. Löwis"
martin at v.loewis.de
Mon Jul 17 23:04:27 CEST 2006
Bruce Christensen wrote:
> Is something like the following close?
Close, yes.
> 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 obj has no __module__ attribute (or if it is None), pickle
(didn't check cPickle) also does
for n, module in sys.module.items():
if "module-ignored": continue
if getattr(module, result, None) is obj:
break # use n as module name
If obj does have a __module__ attribute, it uses __import__
to import the module, just to make sure it gets into sys.modules.
Otherwise, it looks correct.
Regards,
Martin
More information about the Python-Dev
mailing list