1 """Create portable serialized representations of Python objects.
3 See module cPickle for a (much) faster implementation.
4 See module copy_reg for a mechanism for registering custom picklers.
14 dumps(object) -> string
16 loads(string) -> object
26 __version__ =
"$Revision: 5816 $"
29 from copy_reg
import dispatch_table, safe_constructors
35 __all__ = [
"PickleError",
"PicklingError",
"UnpicklingError",
"Pickler",
36 "Unpickler",
"dump",
"dumps",
"load",
"loads"]
38 format_version =
"1.3"
39 compatible_formats = [
"1.0",
"1.1",
"1.2"]
41 mdumps = marshal.dumps
42 mloads = marshal.loads
53 from org.python.core
import PyStringMap
105 __all__.extend([x
for x
in dir()
if re.match(
"[A-Z][A-Z0-9_]+$",x)])
124 return LONG_BINPUT + s
126 return PUT + `i` +
'\n'
135 return LONG_BINGET + s
137 return GET + `i` +
'\n'
139 def save(self, object, pers_save = 0):
152 if (t
is TupleType)
and (len(object) == 0):
167 issc = issubclass(t, TypeType)
180 reduce = dispatch_table[t]
183 reduce = object.__reduce__
184 except AttributeError:
185 raise PicklingError, \
186 "can't pickle %s object: %s" % (`t.__name__`,
193 if type(tup)
is StringType:
197 if type(tup)
is not TupleType:
198 raise PicklingError,
"Value returned by %s must be a " \
203 if (l != 2)
and (l != 3):
204 raise PicklingError,
"tuple returned by %s must contain " \
205 "only two or three elements" % reduce
215 if type(arg_tup)
is not TupleType
and arg_tup
is not None:
216 raise PicklingError,
"Second element of tuple returned " \
217 "by %s must be a tuple" % reduce
222 memo[d] = (memo_len, object)
235 self.
write(PERSID +
str(pid) +
'\n')
238 self.
write(BINPERSID)
248 if state
is not None:
256 dispatch[NoneType] = save_none
263 high_bits = object >> 31
264 if high_bits == 0
or high_bits == -1:
269 if i[-2:] ==
'\000\000':
271 self.
write(BININT1 + i[0])
273 self.
write(BININT2 + i[:2])
275 self.
write(BININT + i)
278 self.
write(INT + `object` +
'\n')
279 dispatch[IntType] = save_int
282 self.
write(LONG + `object` +
'\n')
283 dispatch[LongType] = save_long
287 self.
write(BINFLOAT + pack(
'>d', object))
289 self.
write(FLOAT + `object` +
'\n')
290 dispatch[FloatType] = save_float
300 self.
write(SHORT_BINSTRING + s[0] + object)
302 self.
write(BINSTRING + s + object)
304 self.
write(STRING + `object` +
'\n')
308 memo[d] = (memo_len, object)
309 dispatch[StringType] = save_string
316 encoding = object.encode(
'utf-8')
319 self.
write(BINUNICODE + s + encoding)
321 object = object.replace(
"\\",
"\\u005c")
322 object = object.replace(
"\n",
"\\u000a")
323 self.
write(UNICODE + object.encode(
'raw-unicode-escape') +
'\n')
327 memo[d] = (memo_len, object)
328 dispatch[UnicodeType] = save_unicode
330 if StringType == UnicodeType:
335 unicode = object.isunicode()
339 object = object.encode(
"utf-8")
342 if l < 256
and not unicode:
343 self.
write(SHORT_BINSTRING + s[0] + object)
346 self.
write(BINUNICODE + s + object)
348 self.
write(BINSTRING + s + object)
351 object = object.replace(
"\\",
"\\u005c")
352 object = object.replace(
"\n",
"\\u000a")
353 object = object.encode(
'raw-unicode-escape')
354 self.
write(UNICODE + object +
'\n')
356 self.
write(STRING + `object` +
'\n')
360 memo[d] = (memo_len, object)
361 dispatch[StringType] = save_string
373 for element
in object:
376 if len(object)
and memo.has_key(d):
378 write(POP_MARK + self.
get(memo[d][0]))
381 write(POP * (len(object) + 1) + self.
get(memo[d][0]))
385 self.
write(TUPLE + self.
put(memo_len))
386 memo[d] = (memo_len, object)
387 dispatch[TupleType] = save_tuple
390 self.
write(EMPTY_TUPLE)
406 memo[d] = (memo_len, object)
408 using_appends = (self.
bin and (len(object) > 1))
413 for element
in object:
416 if not using_appends:
421 dispatch[ListType] = save_list
437 memo[d] = (memo_len, object)
439 using_setitems = (self.
bin and (len(object) > 1))
444 items = object.items()
445 for key, value
in items:
449 if not using_setitems:
455 dispatch[DictionaryType] = save_dict
456 if not PyStringMap
is None:
457 dispatch[PyStringMap] = save_dict
461 cls = object.__class__
467 if hasattr(object,
'__getinitargs__'):
468 args = object.__getinitargs__()
470 _keep_alive(args, memo)
486 write(INST + cls.__module__ +
'\n' + cls.__name__ +
'\n' +
489 memo[d] = (memo_len, object)
492 getstate = object.__getstate__
493 except AttributeError:
494 stuff = object.__dict__
497 _keep_alive(stuff, memo)
500 dispatch[InstanceType] = save_inst
507 name = object.__name__
510 module = object.__module__
511 except AttributeError:
516 mod = sys.modules[module]
517 klass = getattr(mod, name)
518 except (ImportError, KeyError, AttributeError):
520 "Can't pickle %r: it's not found as %s.%s" %
521 (object, module, name))
523 if klass
is not object:
525 "Can't pickle %r: it's not the same object as %s.%s" %
526 (object, module, name))
529 write(GLOBAL + module +
'\n' + name +
'\n' +
531 memo[id(object)] = (memo_len, object)
532 dispatch[ClassType] = save_global
533 dispatch[FunctionType] = save_global
534 dispatch[BuiltinFunctionType] = save_global
535 dispatch[TypeType] = save_global
538 def _keep_alive(x, memo):
539 """Keeps a reference to the object x in the memo.
541 Because we remember objects by their id, we have
542 to assure that possibly temporary objects are kept
543 alive by referencing them.
544 We store a reference at the id of the memo, which should
545 normally not be used unless someone tries to deepcopy
559 """Figure out the module in which a class occurs.
561 Search sys.modules for the module.
563 Return a module name.
564 If the class cannot be found, return __main__.
566 if classmap.has_key(cls):
569 for name, module
in sys.modules.items():
570 if name !=
'__main__' and \
571 hasattr(module, clsname)
and \
572 getattr(module, clsname)
is cls:
597 except _Stop, stopinst:
598 return stopinst.value
604 while stack[k]
is not mark: k = k-1
611 dispatch[
''] = load_eof
615 self.
append(self.persistent_load(pid))
616 dispatch[PERSID] = load_persid
624 self.
append(self.persistent_load(pid))
625 dispatch[BINPERSID] = load_binpersid
629 dispatch[NONE] = load_none
637 dispatch[INT] = load_int
641 dispatch[BININT] = load_binint
645 dispatch[BININT1] = load_binint1
649 dispatch[BININT2] = load_binint2
653 dispatch[LONG] = load_long
657 dispatch[FLOAT] = load_float
661 dispatch[BINFLOAT] = load_binfloat
666 raise ValueError,
"insecure string pickle"
668 {
'__builtins__': {}}))
669 dispatch[STRING] = load_string
671 def _is_string_secure(self, s):
672 """Return true if s contains a string that is safe to eval
674 The definition of secure string is based on the implementation
675 in cPickle. s is secure as long as it only contains a quoted
676 string and optional trailing whitespace.
679 if q
not in (
"'",
'"'):
686 i = s.index(q, offset)
697 while j >= offset
and s[j] ==
'\\':
711 dispatch[BINSTRING] = load_binstring
715 dispatch[UNICODE] = load_unicode
720 dispatch[BINUNICODE] = load_binunicode
723 len =
mloads(
'i' + self.
read(1) +
'\000\000\000')
725 dispatch[SHORT_BINSTRING] = load_short_binstring
730 dispatch[TUPLE] = load_tuple
733 self.stack.append(())
734 dispatch[EMPTY_TUPLE] = load_empty_tuple
737 self.stack.append([])
738 dispatch[EMPTY_LIST] = load_empty_list
741 self.stack.append({})
742 dispatch[EMPTY_DICT] = load_empty_dictionary
747 dispatch[LIST] = load_list
752 items = self.
stack[k+1:]
753 for i
in range(0, len(items), 2):
758 dispatch[DICT] = load_dict
768 if (
not args
and type(klass)
is ClassType
and
769 not hasattr(klass,
"__getinitargs__")):
772 value.__class__ = klass
780 if not hasattr(klass,
'__safe_for_unpickling__'):
783 value = apply(klass, args)
784 except TypeError, err:
785 raise TypeError,
"in constructor for %s: %s" % (
786 klass.__name__,
str(err)), sys.exc_info()[2]
788 dispatch[INST] = load_inst
795 args =
tuple(stack[k + 1:])
798 if (
not args
and type(klass)
is ClassType
and
799 not hasattr(klass,
"__getinitargs__")):
802 value.__class__ = klass
809 value = apply(klass, args)
811 dispatch[OBJ] = load_obj
818 dispatch[GLOBAL] = load_global
822 mod = sys.modules[module]
823 klass = getattr(mod, name)
833 if type(callable)
is not ClassType:
834 if not safe_constructors.has_key(callable):
836 safe = callable.__safe_for_unpickling__
837 except AttributeError:
841 raise UnpicklingError,
"%s is not safe for " \
842 "unpickling" % callable
845 value = callable.__basicnew__()
847 value = apply(callable, arg_tup)
849 dispatch[REDUCE] = load_reduce
853 dispatch[POP] = load_pop
858 dispatch[POP_MARK] = load_pop_mark
862 dispatch[DUP] = load_dup
866 dispatch[GET] = load_get
869 i =
mloads(
'i' + self.
read(1) +
'\000\000\000')
871 dispatch[BINGET] = load_binget
876 dispatch[LONG_BINGET] = load_long_binget
880 dispatch[PUT] = load_put
883 i =
mloads(
'i' + self.
read(1) +
'\000\000\000')
885 dispatch[BINPUT] = load_binput
890 dispatch[LONG_BINPUT] = load_long_binput
898 dispatch[APPEND] = load_append
903 list = stack[mark - 1]
904 for i
in range(mark + 1, len(stack)):
905 list.append(stack[i])
908 dispatch[APPENDS] = load_appends
917 dispatch[SETITEM] = load_setitem
922 dict = stack[mark - 1]
923 for i
in range(mark + 1, len(stack), 2):
924 dict[stack[i]] = stack[i + 1]
927 dispatch[SETITEMS] = load_setitems
935 setstate = inst.__setstate__
936 except AttributeError:
938 inst.__dict__.update(value)
944 for k, v
in value.items():
948 dispatch[BUILD] = load_build
952 dispatch[MARK] = load_mark
955 value = self.
stack[-1]
958 dispatch[STOP] = load_stop
968 from cStringIO
import StringIO
970 from StringIO
import StringIO
972 def dump(object, file, bin = 0):
978 return file.getvalue()