Vega strike Python Modules doc  0.5.1
Documentation of the " Modules " folder of Vega strike
 All Data Structures Namespaces Files Functions Variables
pickle.py
Go to the documentation of this file.
1 """Create portable serialized representations of Python objects.
2 
3 See module cPickle for a (much) faster implementation.
4 See module copy_reg for a mechanism for registering custom picklers.
5 
6 Classes:
7 
8  Pickler
9  Unpickler
10 
11 Functions:
12 
13  dump(object, file)
14  dumps(object) -> string
15  load(file) -> object
16  loads(string) -> object
17 
18 Misc variables:
19 
20  __version__
21  format_version
22  compatible_formats
23 
24 """
25 
26 __version__ = "$Revision: 5816 $" # Code version
27 
28 from types import *
29 from copy_reg import dispatch_table, safe_constructors
30 import marshal
31 import sys
32 import struct
33 import re
34 
35 __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
36  "Unpickler", "dump", "dumps", "load", "loads"]
37 
38 format_version = "1.3" # File format version we write
39 compatible_formats = ["1.0", "1.1", "1.2"] # Old format versions we can read
40 
41 mdumps = marshal.dumps
42 mloads = marshal.loads
43 
44 class PickleError(Exception): pass
47 
48 class _Stop(Exception):
49  def __init__(self, value):
50  self.value = value
51 
52 try:
53  from org.python.core import PyStringMap
54 except ImportError:
55  PyStringMap = None
56 
57 try:
58  UnicodeType
59 except NameError:
60  UnicodeType = None
61 
62 
63 MARK = '('
64 STOP = '.'
65 POP = '0'
66 POP_MARK = '1'
67 DUP = '2'
68 FLOAT = 'F'
69 INT = 'I'
70 BININT = 'J'
71 BININT1 = 'K'
72 LONG = 'L'
73 BININT2 = 'M'
74 NONE = 'N'
75 PERSID = 'P'
76 BINPERSID = 'Q'
77 REDUCE = 'R'
78 STRING = 'S'
79 BINSTRING = 'T'
80 SHORT_BINSTRING = 'U'
81 UNICODE = 'V'
82 BINUNICODE = 'X'
83 APPEND = 'a'
84 BUILD = 'b'
85 GLOBAL = 'c'
86 DICT = 'd'
87 EMPTY_DICT = '}'
88 APPENDS = 'e'
89 GET = 'g'
90 BINGET = 'h'
91 INST = 'i'
92 LONG_BINGET = 'j'
93 LIST = 'l'
94 EMPTY_LIST = ']'
95 OBJ = 'o'
96 PUT = 'p'
97 BINPUT = 'q'
98 LONG_BINPUT = 'r'
99 SETITEM = 's'
100 TUPLE = 't'
101 EMPTY_TUPLE = ')'
102 SETITEMS = 'u'
103 BINFLOAT = 'G'
104 
105 __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
106 
107 class Pickler:
108 
109  def __init__(self, file, bin = 0):
110  self.write = file.write
111  self.memo = {}
112  self.bin = bin
113 
114  def dump(self, object):
115  self.save(object)
116  self.write(STOP)
117 
118  def put(self, i):
119  if self.bin:
120  s = mdumps(i)[1:]
121  if i < 256:
122  return BINPUT + s[0]
123 
124  return LONG_BINPUT + s
125 
126  return PUT + `i` + '\n'
127 
128  def get(self, i):
129  if self.bin:
130  s = mdumps(i)[1:]
131 
132  if i < 256:
133  return BINGET + s[0]
134 
135  return LONG_BINGET + s
136 
137  return GET + `i` + '\n'
138 
139  def save(self, object, pers_save = 0):
140  memo = self.memo
141 
142  if not pers_save:
143  pid = self.persistent_id(object)
144  if pid is not None:
145  self.save_pers(pid)
146  return
147 
148  d = id(object)
149 
150  t = type(object)
151 
152  if (t is TupleType) and (len(object) == 0):
153  if self.bin:
154  self.save_empty_tuple(object)
155  else:
156  self.save_tuple(object)
157  return
158 
159  if memo.has_key(d):
160  self.write(self.get(memo[d][0]))
161  return
162 
163  try:
164  f = self.dispatch[t]
165  except KeyError:
166  try:
167  issc = issubclass(t, TypeType)
168  except TypeError: # t is not a class
169  issc = 0
170  if issc:
171  self.save_global(object)
172  return
173 
174  pid = self.inst_persistent_id(object)
175  if pid is not None:
176  self.save_pers(pid)
177  return
178 
179  try:
180  reduce = dispatch_table[t]
181  except KeyError:
182  try:
183  reduce = object.__reduce__
184  except AttributeError:
185  raise PicklingError, \
186  "can't pickle %s object: %s" % (`t.__name__`,
187  `object`)
188  else:
189  tup = reduce()
190  else:
191  tup = reduce(object)
192 
193  if type(tup) is StringType:
194  self.save_global(object, tup)
195  return
196 
197  if type(tup) is not TupleType:
198  raise PicklingError, "Value returned by %s must be a " \
199  "tuple" % reduce
200 
201  l = len(tup)
202 
203  if (l != 2) and (l != 3):
204  raise PicklingError, "tuple returned by %s must contain " \
205  "only two or three elements" % reduce
206 
207  callable = tup[0]
208  arg_tup = tup[1]
209 
210  if l > 2:
211  state = tup[2]
212  else:
213  state = None
214 
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
218 
219  self.save_reduce(callable, arg_tup, state)
220  memo_len = len(memo)
221  self.write(self.put(memo_len))
222  memo[d] = (memo_len, object)
223  return
224 
225  f(self, object)
226 
227  def persistent_id(self, object):
228  return None
229 
230  def inst_persistent_id(self, object):
231  return None
232 
233  def save_pers(self, pid):
234  if not self.bin:
235  self.write(PERSID + str(pid) + '\n')
236  else:
237  self.save(pid, 1)
238  self.write(BINPERSID)
239 
240  def save_reduce(self, callable, arg_tup, state = None):
241  write = self.write
242  save = self.save
243 
244  save(callable)
245  save(arg_tup)
246  write(REDUCE)
247 
248  if state is not None:
249  save(state)
250  write(BUILD)
251 
252  dispatch = {}
253 
254  def save_none(self, object):
255  self.write(NONE)
256  dispatch[NoneType] = save_none
257 
258  def save_int(self, object):
259  if self.bin:
260  # If the int is small enough to fit in a signed 4-byte 2's-comp
261  # format, we can store it more efficiently than the general
262  # case.
263  high_bits = object >> 31 # note that Python shift sign-extends
264  if high_bits == 0 or high_bits == -1:
265  # All high bits are copies of bit 2**31, so the value
266  # fits in a 4-byte signed int.
267  i = mdumps(object)[1:]
268  assert len(i) == 4
269  if i[-2:] == '\000\000': # fits in 2-byte unsigned int
270  if i[-3] == '\000': # fits in 1-byte unsigned int
271  self.write(BININT1 + i[0])
272  else:
273  self.write(BININT2 + i[:2])
274  else:
275  self.write(BININT + i)
276  return
277  # Text pickle, or int too big to fit in signed 4-byte format.
278  self.write(INT + `object` + '\n')
279  dispatch[IntType] = save_int
280 
281  def save_long(self, object):
282  self.write(LONG + `object` + '\n')
283  dispatch[LongType] = save_long
284 
285  def save_float(self, object, pack=struct.pack):
286  if self.bin:
287  self.write(BINFLOAT + pack('>d', object))
288  else:
289  self.write(FLOAT + `object` + '\n')
290  dispatch[FloatType] = save_float
291 
292  def save_string(self, object):
293  d = id(object)
294  memo = self.memo
295 
296  if self.bin:
297  l = len(object)
298  s = mdumps(l)[1:]
299  if l < 256:
300  self.write(SHORT_BINSTRING + s[0] + object)
301  else:
302  self.write(BINSTRING + s + object)
303  else:
304  self.write(STRING + `object` + '\n')
305 
306  memo_len = len(memo)
307  self.write(self.put(memo_len))
308  memo[d] = (memo_len, object)
309  dispatch[StringType] = save_string
310 
311  def save_unicode(self, object):
312  d = id(object)
313  memo = self.memo
314 
315  if self.bin:
316  encoding = object.encode('utf-8')
317  l = len(encoding)
318  s = mdumps(l)[1:]
319  self.write(BINUNICODE + s + encoding)
320  else:
321  object = object.replace("\\", "\\u005c")
322  object = object.replace("\n", "\\u000a")
323  self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
324 
325  memo_len = len(memo)
326  self.write(self.put(memo_len))
327  memo[d] = (memo_len, object)
328  dispatch[UnicodeType] = save_unicode
329 
330  if StringType == UnicodeType:
331  # This is true for Jython
332  def save_string(self, object):
333  d = id(object)
334  memo = self.memo
335  unicode = object.isunicode()
336 
337  if self.bin:
338  if unicode:
339  object = object.encode("utf-8")
340  l = len(object)
341  s = mdumps(l)[1:]
342  if l < 256 and not unicode:
343  self.write(SHORT_BINSTRING + s[0] + object)
344  else:
345  if unicode:
346  self.write(BINUNICODE + s + object)
347  else:
348  self.write(BINSTRING + s + object)
349  else:
350  if unicode:
351  object = object.replace("\\", "\\u005c")
352  object = object.replace("\n", "\\u000a")
353  object = object.encode('raw-unicode-escape')
354  self.write(UNICODE + object + '\n')
355  else:
356  self.write(STRING + `object` + '\n')
357 
358  memo_len = len(memo)
359  self.write(self.put(memo_len))
360  memo[d] = (memo_len, object)
361  dispatch[StringType] = save_string
362 
363  def save_tuple(self, object):
364 
365  write = self.write
366  save = self.save
367  memo = self.memo
368 
369  d = id(object)
370 
371  write(MARK)
372 
373  for element in object:
374  save(element)
375 
376  if len(object) and memo.has_key(d):
377  if self.bin:
378  write(POP_MARK + self.get(memo[d][0]))
379  return
380 
381  write(POP * (len(object) + 1) + self.get(memo[d][0]))
382  return
383 
384  memo_len = len(memo)
385  self.write(TUPLE + self.put(memo_len))
386  memo[d] = (memo_len, object)
387  dispatch[TupleType] = save_tuple
388 
389  def save_empty_tuple(self, object):
390  self.write(EMPTY_TUPLE)
391 
392  def save_list(self, object):
393  d = id(object)
394 
395  write = self.write
396  save = self.save
397  memo = self.memo
398 
399  if self.bin:
400  write(EMPTY_LIST)
401  else:
402  write(MARK + LIST)
403 
404  memo_len = len(memo)
405  write(self.put(memo_len))
406  memo[d] = (memo_len, object)
407 
408  using_appends = (self.bin and (len(object) > 1))
409 
410  if using_appends:
411  write(MARK)
412 
413  for element in object:
414  save(element)
415 
416  if not using_appends:
417  write(APPEND)
418 
419  if using_appends:
420  write(APPENDS)
421  dispatch[ListType] = save_list
422 
423  def save_dict(self, object):
424  d = id(object)
425 
426  write = self.write
427  save = self.save
428  memo = self.memo
429 
430  if self.bin:
431  write(EMPTY_DICT)
432  else:
433  write(MARK + DICT)
434 
435  memo_len = len(memo)
436  self.write(self.put(memo_len))
437  memo[d] = (memo_len, object)
438 
439  using_setitems = (self.bin and (len(object) > 1))
440 
441  if using_setitems:
442  write(MARK)
443 
444  items = object.items()
445  for key, value in items:
446  save(key)
447  save(value)
448 
449  if not using_setitems:
450  write(SETITEM)
451 
452  if using_setitems:
453  write(SETITEMS)
454 
455  dispatch[DictionaryType] = save_dict
456  if not PyStringMap is None:
457  dispatch[PyStringMap] = save_dict
458 
459  def save_inst(self, object):
460  d = id(object)
461  cls = object.__class__
462 
463  memo = self.memo
464  write = self.write
465  save = self.save
466 
467  if hasattr(object, '__getinitargs__'):
468  args = object.__getinitargs__()
469  len(args) # XXX Assert it's a sequence
470  _keep_alive(args, memo)
471  else:
472  args = ()
473 
474  write(MARK)
475 
476  if self.bin:
477  save(cls)
478 
479  for arg in args:
480  save(arg)
481 
482  memo_len = len(memo)
483  if self.bin:
484  write(OBJ + self.put(memo_len))
485  else:
486  write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
487  self.put(memo_len))
488 
489  memo[d] = (memo_len, object)
490 
491  try:
492  getstate = object.__getstate__
493  except AttributeError:
494  stuff = object.__dict__
495  else:
496  stuff = getstate()
497  _keep_alive(stuff, memo)
498  save(stuff)
499  write(BUILD)
500  dispatch[InstanceType] = save_inst
501 
502  def save_global(self, object, name = None):
503  write = self.write
504  memo = self.memo
505 
506  if name is None:
507  name = object.__name__
508 
509  try:
510  module = object.__module__
511  except AttributeError:
512  module = whichmodule(object, name)
513 
514  try:
515  __import__(module)
516  mod = sys.modules[module]
517  klass = getattr(mod, name)
518  except (ImportError, KeyError, AttributeError):
519  raise PicklingError(
520  "Can't pickle %r: it's not found as %s.%s" %
521  (object, module, name))
522  else:
523  if klass is not object:
524  raise PicklingError(
525  "Can't pickle %r: it's not the same object as %s.%s" %
526  (object, module, name))
527 
528  memo_len = len(memo)
529  write(GLOBAL + module + '\n' + name + '\n' +
530  self.put(memo_len))
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
536 
537 
538 def _keep_alive(x, memo):
539  """Keeps a reference to the object x in the memo.
540 
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
546  the memo itself...
547  """
548  try:
549  memo[id(memo)].append(x)
550  except KeyError:
551  # aha, this is the first one :-)
552  memo[id(memo)]=[x]
553 
554 
555 classmap = {}
556 
557 # This is no longer used to find classes, but still for functions
558 def whichmodule(cls, clsname):
559  """Figure out the module in which a class occurs.
560 
561  Search sys.modules for the module.
562  Cache in classmap.
563  Return a module name.
564  If the class cannot be found, return __main__.
565  """
566  if classmap.has_key(cls):
567  return classmap[cls]
568 
569  for name, module in sys.modules.items():
570  if name != '__main__' and \
571  hasattr(module, clsname) and \
572  getattr(module, clsname) is cls:
573  break
574  else:
575  name = '__main__'
576  classmap[cls] = name
577  return name
578 
579 
580 class Unpickler:
581 
582  def __init__(self, file):
583  self.readline = file.readline
584  self.read = file.read
585  self.memo = {}
586 
587  def load(self):
588  self.mark = object() # any new unique object
589  self.stack = []
590  self.append = self.stack.append
591  read = self.read
592  dispatch = self.dispatch
593  try:
594  while 1:
595  key = read(1)
596  dispatch[key](self)
597  except _Stop, stopinst:
598  return stopinst.value
599 
600  def marker(self):
601  stack = self.stack
602  mark = self.mark
603  k = len(stack)-1
604  while stack[k] is not mark: k = k-1
605  return k
606 
607  dispatch = {}
608 
609  def load_eof(self):
610  raise EOFError
611  dispatch[''] = load_eof
612 
613  def load_persid(self):
614  pid = self.readline()[:-1]
615  self.append(self.persistent_load(pid))
616  dispatch[PERSID] = load_persid
617 
618  def load_binpersid(self):
619  stack = self.stack
620 
621  pid = stack[-1]
622  del stack[-1]
623 
624  self.append(self.persistent_load(pid))
625  dispatch[BINPERSID] = load_binpersid
626 
627  def load_none(self):
628  self.append(None)
629  dispatch[NONE] = load_none
630 
631  def load_int(self):
632  data = self.readline()
633  try:
634  self.append(int(data))
635  except ValueError:
636  self.append(long(data))
637  dispatch[INT] = load_int
638 
639  def load_binint(self):
640  self.append(mloads('i' + self.read(4)))
641  dispatch[BININT] = load_binint
642 
643  def load_binint1(self):
644  self.append(mloads('i' + self.read(1) + '\000\000\000'))
645  dispatch[BININT1] = load_binint1
646 
647  def load_binint2(self):
648  self.append(mloads('i' + self.read(2) + '\000\000'))
649  dispatch[BININT2] = load_binint2
650 
651  def load_long(self):
652  self.append(long(self.readline()[:-1], 0))
653  dispatch[LONG] = load_long
654 
655  def load_float(self):
656  self.append(float(self.readline()[:-1]))
657  dispatch[FLOAT] = load_float
658 
659  def load_binfloat(self, unpack=struct.unpack):
660  self.append(unpack('>d', self.read(8))[0])
661  dispatch[BINFLOAT] = load_binfloat
662 
663  def load_string(self):
664  rep = self.readline()[:-1]
665  if not self._is_string_secure(rep):
666  raise ValueError, "insecure string pickle"
667  self.append(eval(rep,
668  {'__builtins__': {}})) # Let's be careful
669  dispatch[STRING] = load_string
670 
671  def _is_string_secure(self, s):
672  """Return true if s contains a string that is safe to eval
673 
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.
677  """
678  q = s[0]
679  if q not in ("'", '"'):
680  return 0
681  # find the closing quote
682  offset = 1
683  i = None
684  while 1:
685  try:
686  i = s.index(q, offset)
687  except ValueError:
688  # if there is an error the first time, there is no
689  # close quote
690  if offset == 1:
691  return 0
692  if s[i-1] != '\\':
693  break
694  # check to see if this one is escaped
695  nslash = 0
696  j = i - 1
697  while j >= offset and s[j] == '\\':
698  j = j - 1
699  nslash = nslash + 1
700  if nslash % 2 == 0:
701  break
702  offset = i + 1
703  for c in s[i+1:]:
704  if ord(c) > 32:
705  return 0
706  return 1
707 
708  def load_binstring(self):
709  len = mloads('i' + self.read(4))
710  self.append(self.read(len))
711  dispatch[BINSTRING] = load_binstring
712 
713  def load_unicode(self):
714  self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
715  dispatch[UNICODE] = load_unicode
716 
717  def load_binunicode(self):
718  len = mloads('i' + self.read(4))
719  self.append(unicode(self.read(len),'utf-8'))
720  dispatch[BINUNICODE] = load_binunicode
721 
723  len = mloads('i' + self.read(1) + '\000\000\000')
724  self.append(self.read(len))
725  dispatch[SHORT_BINSTRING] = load_short_binstring
726 
727  def load_tuple(self):
728  k = self.marker()
729  self.stack[k:] = [tuple(self.stack[k+1:])]
730  dispatch[TUPLE] = load_tuple
731 
732  def load_empty_tuple(self):
733  self.stack.append(())
734  dispatch[EMPTY_TUPLE] = load_empty_tuple
735 
736  def load_empty_list(self):
737  self.stack.append([])
738  dispatch[EMPTY_LIST] = load_empty_list
739 
741  self.stack.append({})
742  dispatch[EMPTY_DICT] = load_empty_dictionary
743 
744  def load_list(self):
745  k = self.marker()
746  self.stack[k:] = [self.stack[k+1:]]
747  dispatch[LIST] = load_list
748 
749  def load_dict(self):
750  k = self.marker()
751  d = {}
752  items = self.stack[k+1:]
753  for i in range(0, len(items), 2):
754  key = items[i]
755  value = items[i+1]
756  d[key] = value
757  self.stack[k:] = [d]
758  dispatch[DICT] = load_dict
759 
760  def load_inst(self):
761  k = self.marker()
762  args = tuple(self.stack[k+1:])
763  del self.stack[k:]
764  module = self.readline()[:-1]
765  name = self.readline()[:-1]
766  klass = self.find_class(module, name)
767  instantiated = 0
768  if (not args and type(klass) is ClassType and
769  not hasattr(klass, "__getinitargs__")):
770  try:
771  value = _EmptyClass()
772  value.__class__ = klass
773  instantiated = 1
774  except RuntimeError:
775  # In restricted execution, assignment to inst.__class__ is
776  # prohibited
777  pass
778  if not instantiated:
779  try:
780  if not hasattr(klass, '__safe_for_unpickling__'):
781  raise UnpicklingError('%s is not safe for unpickling' %
782  klass)
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]
787  self.append(value)
788  dispatch[INST] = load_inst
789 
790  def load_obj(self):
791  stack = self.stack
792  k = self.marker()
793  klass = stack[k + 1]
794  del stack[k + 1]
795  args = tuple(stack[k + 1:])
796  del stack[k:]
797  instantiated = 0
798  if (not args and type(klass) is ClassType and
799  not hasattr(klass, "__getinitargs__")):
800  try:
801  value = _EmptyClass()
802  value.__class__ = klass
803  instantiated = 1
804  except RuntimeError:
805  # In restricted execution, assignment to inst.__class__ is
806  # prohibited
807  pass
808  if not instantiated:
809  value = apply(klass, args)
810  self.append(value)
811  dispatch[OBJ] = load_obj
812 
813  def load_global(self):
814  module = self.readline()[:-1]
815  name = self.readline()[:-1]
816  klass = self.find_class(module, name)
817  self.append(klass)
818  dispatch[GLOBAL] = load_global
819 
820  def find_class(self, module, name):
821  __import__(module)
822  mod = sys.modules[module]
823  klass = getattr(mod, name)
824  return klass
825 
826  def load_reduce(self):
827  stack = self.stack
828 
829  callable = stack[-2]
830  arg_tup = stack[-1]
831  del stack[-2:]
832 
833  if type(callable) is not ClassType:
834  if not safe_constructors.has_key(callable):
835  try:
836  safe = callable.__safe_for_unpickling__
837  except AttributeError:
838  safe = None
839 
840  if not safe:
841  raise UnpicklingError, "%s is not safe for " \
842  "unpickling" % callable
843 
844  if arg_tup is None:
845  value = callable.__basicnew__()
846  else:
847  value = apply(callable, arg_tup)
848  self.append(value)
849  dispatch[REDUCE] = load_reduce
850 
851  def load_pop(self):
852  del self.stack[-1]
853  dispatch[POP] = load_pop
854 
855  def load_pop_mark(self):
856  k = self.marker()
857  del self.stack[k:]
858  dispatch[POP_MARK] = load_pop_mark
859 
860  def load_dup(self):
861  self.append(self.stack[-1])
862  dispatch[DUP] = load_dup
863 
864  def load_get(self):
865  self.append(self.memo[self.readline()[:-1]])
866  dispatch[GET] = load_get
867 
868  def load_binget(self):
869  i = mloads('i' + self.read(1) + '\000\000\000')
870  self.append(self.memo[`i`])
871  dispatch[BINGET] = load_binget
872 
873  def load_long_binget(self):
874  i = mloads('i' + self.read(4))
875  self.append(self.memo[`i`])
876  dispatch[LONG_BINGET] = load_long_binget
877 
878  def load_put(self):
879  self.memo[self.readline()[:-1]] = self.stack[-1]
880  dispatch[PUT] = load_put
881 
882  def load_binput(self):
883  i = mloads('i' + self.read(1) + '\000\000\000')
884  self.memo[`i`] = self.stack[-1]
885  dispatch[BINPUT] = load_binput
886 
887  def load_long_binput(self):
888  i = mloads('i' + self.read(4))
889  self.memo[`i`] = self.stack[-1]
890  dispatch[LONG_BINPUT] = load_long_binput
891 
892  def load_append(self):
893  stack = self.stack
894  value = stack[-1]
895  del stack[-1]
896  list = stack[-1]
897  list.append(value)
898  dispatch[APPEND] = load_append
899 
900  def load_appends(self):
901  stack = self.stack
902  mark = self.marker()
903  list = stack[mark - 1]
904  for i in range(mark + 1, len(stack)):
905  list.append(stack[i])
906 
907  del stack[mark:]
908  dispatch[APPENDS] = load_appends
909 
910  def load_setitem(self):
911  stack = self.stack
912  value = stack[-1]
913  key = stack[-2]
914  del stack[-2:]
915  dict = stack[-1]
916  dict[key] = value
917  dispatch[SETITEM] = load_setitem
918 
919  def load_setitems(self):
920  stack = self.stack
921  mark = self.marker()
922  dict = stack[mark - 1]
923  for i in range(mark + 1, len(stack), 2):
924  dict[stack[i]] = stack[i + 1]
925 
926  del stack[mark:]
927  dispatch[SETITEMS] = load_setitems
928 
929  def load_build(self):
930  stack = self.stack
931  value = stack[-1]
932  del stack[-1]
933  inst = stack[-1]
934  try:
935  setstate = inst.__setstate__
936  except AttributeError:
937  try:
938  inst.__dict__.update(value)
939  except RuntimeError:
940  # XXX In restricted execution, the instance's __dict__ is not
941  # accessible. Use the old way of unpickling the instance
942  # variables. This is a semantic different when unpickling in
943  # restricted vs. unrestricted modes.
944  for k, v in value.items():
945  setattr(inst, k, v)
946  else:
947  setstate(value)
948  dispatch[BUILD] = load_build
949 
950  def load_mark(self):
951  self.append(self.mark)
952  dispatch[MARK] = load_mark
953 
954  def load_stop(self):
955  value = self.stack[-1]
956  del self.stack[-1]
957  raise _Stop(value)
958  dispatch[STOP] = load_stop
959 
960 # Helper class for load_inst/load_obj
961 
963  pass
964 
965 # Shorthands
966 
967 try:
968  from cStringIO import StringIO
969 except ImportError:
970  from StringIO import StringIO
971 
972 def dump(object, file, bin = 0):
973  Pickler(file, bin).dump(object)
974 
975 def dumps(object, bin = 0):
976  file = StringIO()
977  Pickler(file, bin).dump(object)
978  return file.getvalue()
979 
980 def load(file):
981  return Unpickler(file).load()
982 
983 def loads(str):
984  file = StringIO(str)
985  return Unpickler(file).load()