PageRenderTime 56ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/pickle.py

http://github.com/IronLanguages/main
Python | 1391 lines | 1219 code | 66 blank | 106 comment | 49 complexity | aaa8cd69a9abdd4d130b9ea4748261bb MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """Create portable serialized representations of Python objects.
  2. See module cPickle for a (much) faster implementation.
  3. See module copy_reg for a mechanism for registering custom picklers.
  4. See module pickletools source for extensive comments.
  5. Classes:
  6. Pickler
  7. Unpickler
  8. Functions:
  9. dump(object, file)
  10. dumps(object) -> string
  11. load(file) -> object
  12. loads(string) -> object
  13. Misc variables:
  14. __version__
  15. format_version
  16. compatible_formats
  17. """
  18. __version__ = "$Revision$" # Code version
  19. from types import *
  20. from copy_reg import dispatch_table
  21. from copy_reg import _extension_registry, _inverted_registry, _extension_cache
  22. import marshal
  23. import sys
  24. import struct
  25. import re
  26. __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
  27. "Unpickler", "dump", "dumps", "load", "loads"]
  28. # These are purely informational; no code uses these.
  29. format_version = "2.0" # File format version we write
  30. compatible_formats = ["1.0", # Original protocol 0
  31. "1.1", # Protocol 0 with INST added
  32. "1.2", # Original protocol 1
  33. "1.3", # Protocol 1 with BINFLOAT added
  34. "2.0", # Protocol 2
  35. ] # Old format versions we can read
  36. # Keep in synch with cPickle. This is the highest protocol number we
  37. # know how to read.
  38. HIGHEST_PROTOCOL = 2
  39. # Why use struct.pack() for pickling but marshal.loads() for
  40. # unpickling? struct.pack() is 40% faster than marshal.dumps(), but
  41. # marshal.loads() is twice as fast as struct.unpack()!
  42. mloads = marshal.loads
  43. class PickleError(Exception):
  44. """A common base class for the other pickling exceptions."""
  45. pass
  46. class PicklingError(PickleError):
  47. """This exception is raised when an unpicklable object is passed to the
  48. dump() method.
  49. """
  50. pass
  51. class UnpicklingError(PickleError):
  52. """This exception is raised when there is a problem unpickling an object,
  53. such as a security violation.
  54. Note that other exceptions may also be raised during unpickling, including
  55. (but not necessarily limited to) AttributeError, EOFError, ImportError,
  56. and IndexError.
  57. """
  58. pass
  59. # An instance of _Stop is raised by Unpickler.load_stop() in response to
  60. # the STOP opcode, passing the object that is the result of unpickling.
  61. class _Stop(Exception):
  62. def __init__(self, value):
  63. self.value = value
  64. # Jython has PyStringMap; it's a dict subclass with string keys
  65. try:
  66. from org.python.core import PyStringMap
  67. except ImportError:
  68. PyStringMap = None
  69. # UnicodeType may or may not be exported (normally imported from types)
  70. try:
  71. UnicodeType
  72. except NameError:
  73. UnicodeType = None
  74. # Pickle opcodes. See pickletools.py for extensive docs. The listing
  75. # here is in kind-of alphabetical order of 1-character pickle code.
  76. # pickletools groups them by purpose.
  77. MARK = '(' # push special markobject on stack
  78. STOP = '.' # every pickle ends with STOP
  79. POP = '0' # discard topmost stack item
  80. POP_MARK = '1' # discard stack top through topmost markobject
  81. DUP = '2' # duplicate top stack item
  82. FLOAT = 'F' # push float object; decimal string argument
  83. INT = 'I' # push integer or bool; decimal string argument
  84. BININT = 'J' # push four-byte signed int
  85. BININT1 = 'K' # push 1-byte unsigned int
  86. LONG = 'L' # push long; decimal string argument
  87. BININT2 = 'M' # push 2-byte unsigned int
  88. NONE = 'N' # push None
  89. PERSID = 'P' # push persistent object; id is taken from string arg
  90. BINPERSID = 'Q' # " " " ; " " " " stack
  91. REDUCE = 'R' # apply callable to argtuple, both on stack
  92. STRING = 'S' # push string; NL-terminated string argument
  93. BINSTRING = 'T' # push string; counted binary string argument
  94. SHORT_BINSTRING = 'U' # " " ; " " " " < 256 bytes
  95. UNICODE = 'V' # push Unicode string; raw-unicode-escaped'd argument
  96. BINUNICODE = 'X' # " " " ; counted UTF-8 string argument
  97. APPEND = 'a' # append stack top to list below it
  98. BUILD = 'b' # call __setstate__ or __dict__.update()
  99. GLOBAL = 'c' # push self.find_class(modname, name); 2 string args
  100. DICT = 'd' # build a dict from stack items
  101. EMPTY_DICT = '}' # push empty dict
  102. APPENDS = 'e' # extend list on stack by topmost stack slice
  103. GET = 'g' # push item from memo on stack; index is string arg
  104. BINGET = 'h' # " " " " " " ; " " 1-byte arg
  105. INST = 'i' # build & push class instance
  106. LONG_BINGET = 'j' # push item from memo on stack; index is 4-byte arg
  107. LIST = 'l' # build list from topmost stack items
  108. EMPTY_LIST = ']' # push empty list
  109. OBJ = 'o' # build & push class instance
  110. PUT = 'p' # store stack top in memo; index is string arg
  111. BINPUT = 'q' # " " " " " ; " " 1-byte arg
  112. LONG_BINPUT = 'r' # " " " " " ; " " 4-byte arg
  113. SETITEM = 's' # add key+value pair to dict
  114. TUPLE = 't' # build tuple from topmost stack items
  115. EMPTY_TUPLE = ')' # push empty tuple
  116. SETITEMS = 'u' # modify dict by adding topmost key+value pairs
  117. BINFLOAT = 'G' # push float; arg is 8-byte float encoding
  118. TRUE = 'I01\n' # not an opcode; see INT docs in pickletools.py
  119. FALSE = 'I00\n' # not an opcode; see INT docs in pickletools.py
  120. # Protocol 2
  121. PROTO = '\x80' # identify pickle protocol
  122. NEWOBJ = '\x81' # build object by applying cls.__new__ to argtuple
  123. EXT1 = '\x82' # push object from extension registry; 1-byte index
  124. EXT2 = '\x83' # ditto, but 2-byte index
  125. EXT4 = '\x84' # ditto, but 4-byte index
  126. TUPLE1 = '\x85' # build 1-tuple from stack top
  127. TUPLE2 = '\x86' # build 2-tuple from two topmost stack items
  128. TUPLE3 = '\x87' # build 3-tuple from three topmost stack items
  129. NEWTRUE = '\x88' # push True
  130. NEWFALSE = '\x89' # push False
  131. LONG1 = '\x8a' # push long from < 256 bytes
  132. LONG4 = '\x8b' # push really big long
  133. _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
  134. __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
  135. del x
  136. # Pickling machinery
  137. class Pickler:
  138. def __init__(self, file, protocol=None):
  139. """This takes a file-like object for writing a pickle data stream.
  140. The optional protocol argument tells the pickler to use the
  141. given protocol; supported protocols are 0, 1, 2. The default
  142. protocol is 0, to be backwards compatible. (Protocol 0 is the
  143. only protocol that can be written to a file opened in text
  144. mode and read back successfully. When using a protocol higher
  145. than 0, make sure the file is opened in binary mode, both when
  146. pickling and unpickling.)
  147. Protocol 1 is more efficient than protocol 0; protocol 2 is
  148. more efficient than protocol 1.
  149. Specifying a negative protocol version selects the highest
  150. protocol version supported. The higher the protocol used, the
  151. more recent the version of Python needed to read the pickle
  152. produced.
  153. The file parameter must have a write() method that accepts a single
  154. string argument. It can thus be an open file object, a StringIO
  155. object, or any other custom object that meets this interface.
  156. """
  157. if protocol is None:
  158. protocol = 0
  159. if protocol < 0:
  160. protocol = HIGHEST_PROTOCOL
  161. elif not 0 <= protocol <= HIGHEST_PROTOCOL:
  162. raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
  163. self.write = file.write
  164. self.memo = {}
  165. self.proto = int(protocol)
  166. self.bin = protocol >= 1
  167. self.fast = 0
  168. def clear_memo(self):
  169. """Clears the pickler's "memo".
  170. The memo is the data structure that remembers which objects the
  171. pickler has already seen, so that shared or recursive objects are
  172. pickled by reference and not by value. This method is useful when
  173. re-using picklers.
  174. """
  175. self.memo.clear()
  176. def dump(self, obj):
  177. """Write a pickled representation of obj to the open file."""
  178. if self.proto >= 2:
  179. self.write(PROTO + chr(self.proto))
  180. self.save(obj)
  181. self.write(STOP)
  182. def memoize(self, obj):
  183. """Store an object in the memo."""
  184. # The Pickler memo is a dictionary mapping object ids to 2-tuples
  185. # that contain the Unpickler memo key and the object being memoized.
  186. # The memo key is written to the pickle and will become
  187. # the key in the Unpickler's memo. The object is stored in the
  188. # Pickler memo so that transient objects are kept alive during
  189. # pickling.
  190. # The use of the Unpickler memo length as the memo key is just a
  191. # convention. The only requirement is that the memo values be unique.
  192. # But there appears no advantage to any other scheme, and this
  193. # scheme allows the Unpickler memo to be implemented as a plain (but
  194. # growable) array, indexed by memo key.
  195. if self.fast:
  196. return
  197. assert id(obj) not in self.memo
  198. memo_len = len(self.memo)
  199. self.write(self.put(memo_len))
  200. self.memo[id(obj)] = memo_len, obj
  201. # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
  202. def put(self, i, pack=struct.pack):
  203. if self.bin:
  204. if i < 256:
  205. return BINPUT + chr(i)
  206. else:
  207. return LONG_BINPUT + pack("<i", i)
  208. return PUT + repr(i) + '\n'
  209. # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
  210. def get(self, i, pack=struct.pack):
  211. if self.bin:
  212. if i < 256:
  213. return BINGET + chr(i)
  214. else:
  215. return LONG_BINGET + pack("<i", i)
  216. return GET + repr(i) + '\n'
  217. def save(self, obj):
  218. # Check for persistent id (defined by a subclass)
  219. pid = self.persistent_id(obj)
  220. if pid:
  221. self.save_pers(pid)
  222. return
  223. # Check the memo
  224. x = self.memo.get(id(obj))
  225. if x:
  226. self.write(self.get(x[0]))
  227. return
  228. # Check the type dispatch table
  229. t = type(obj)
  230. f = self.dispatch.get(t)
  231. if f:
  232. f(self, obj) # Call unbound method with explicit self
  233. return
  234. # Check for a class with a custom metaclass; treat as regular class
  235. try:
  236. issc = issubclass(t, TypeType)
  237. except TypeError: # t is not a class (old Boost; see SF #502085)
  238. issc = 0
  239. if issc:
  240. self.save_global(obj)
  241. return
  242. # Check copy_reg.dispatch_table
  243. reduce = dispatch_table.get(t)
  244. if reduce:
  245. rv = reduce(obj)
  246. else:
  247. # Check for a __reduce_ex__ method, fall back to __reduce__
  248. reduce = getattr(obj, "__reduce_ex__", None)
  249. if reduce:
  250. rv = reduce(self.proto)
  251. else:
  252. reduce = getattr(obj, "__reduce__", None)
  253. if reduce:
  254. rv = reduce()
  255. else:
  256. raise PicklingError("Can't pickle %r object: %r" %
  257. (t.__name__, obj))
  258. # Check for string returned by reduce(), meaning "save as global"
  259. if type(rv) is StringType:
  260. self.save_global(obj, rv)
  261. return
  262. # Assert that reduce() returned a tuple
  263. if type(rv) is not TupleType:
  264. raise PicklingError("%s must return string or tuple" % reduce)
  265. # Assert that it returned an appropriately sized tuple
  266. l = len(rv)
  267. if not (2 <= l <= 5):
  268. raise PicklingError("Tuple returned by %s must have "
  269. "two to five elements" % reduce)
  270. # Save the reduce() output and finally memoize the object
  271. self.save_reduce(obj=obj, *rv)
  272. def persistent_id(self, obj):
  273. # This exists so a subclass can override it
  274. return None
  275. def save_pers(self, pid):
  276. # Save a persistent id reference
  277. if self.bin:
  278. self.save(pid)
  279. self.write(BINPERSID)
  280. else:
  281. self.write(PERSID + str(pid) + '\n')
  282. def save_reduce(self, func, args, state=None,
  283. listitems=None, dictitems=None, obj=None):
  284. # This API is called by some subclasses
  285. # Assert that args is a tuple or None
  286. if not isinstance(args, TupleType):
  287. raise PicklingError("args from reduce() should be a tuple")
  288. # Assert that func is callable
  289. if not hasattr(func, '__call__'):
  290. raise PicklingError("func from reduce should be callable")
  291. save = self.save
  292. write = self.write
  293. # Protocol 2 special case: if func's name is __newobj__, use NEWOBJ
  294. if self.proto >= 2 and getattr(func, "__name__", "") == "__newobj__":
  295. # A __reduce__ implementation can direct protocol 2 to
  296. # use the more efficient NEWOBJ opcode, while still
  297. # allowing protocol 0 and 1 to work normally. For this to
  298. # work, the function returned by __reduce__ should be
  299. # called __newobj__, and its first argument should be a
  300. # new-style class. The implementation for __newobj__
  301. # should be as follows, although pickle has no way to
  302. # verify this:
  303. #
  304. # def __newobj__(cls, *args):
  305. # return cls.__new__(cls, *args)
  306. #
  307. # Protocols 0 and 1 will pickle a reference to __newobj__,
  308. # while protocol 2 (and above) will pickle a reference to
  309. # cls, the remaining args tuple, and the NEWOBJ code,
  310. # which calls cls.__new__(cls, *args) at unpickling time
  311. # (see load_newobj below). If __reduce__ returns a
  312. # three-tuple, the state from the third tuple item will be
  313. # pickled regardless of the protocol, calling __setstate__
  314. # at unpickling time (see load_build below).
  315. #
  316. # Note that no standard __newobj__ implementation exists;
  317. # you have to provide your own. This is to enforce
  318. # compatibility with Python 2.2 (pickles written using
  319. # protocol 0 or 1 in Python 2.3 should be unpicklable by
  320. # Python 2.2).
  321. cls = args[0]
  322. if not hasattr(cls, "__new__"):
  323. raise PicklingError(
  324. "args[0] from __newobj__ args has no __new__")
  325. if obj is not None and cls is not obj.__class__:
  326. raise PicklingError(
  327. "args[0] from __newobj__ args has the wrong class")
  328. args = args[1:]
  329. save(cls)
  330. save(args)
  331. write(NEWOBJ)
  332. else:
  333. save(func)
  334. save(args)
  335. write(REDUCE)
  336. if obj is not None:
  337. self.memoize(obj)
  338. # More new special cases (that work with older protocols as
  339. # well): when __reduce__ returns a tuple with 4 or 5 items,
  340. # the 4th and 5th item should be iterators that provide list
  341. # items and dict items (as (key, value) tuples), or None.
  342. if listitems is not None:
  343. self._batch_appends(listitems)
  344. if dictitems is not None:
  345. self._batch_setitems(dictitems)
  346. if state is not None:
  347. save(state)
  348. write(BUILD)
  349. # Methods below this point are dispatched through the dispatch table
  350. dispatch = {}
  351. def save_none(self, obj):
  352. self.write(NONE)
  353. dispatch[NoneType] = save_none
  354. def save_bool(self, obj):
  355. if self.proto >= 2:
  356. self.write(obj and NEWTRUE or NEWFALSE)
  357. else:
  358. self.write(obj and TRUE or FALSE)
  359. dispatch[bool] = save_bool
  360. def save_int(self, obj, pack=struct.pack):
  361. if self.bin:
  362. # If the int is small enough to fit in a signed 4-byte 2's-comp
  363. # format, we can store it more efficiently than the general
  364. # case.
  365. # First one- and two-byte unsigned ints:
  366. if obj >= 0:
  367. if obj <= 0xff:
  368. self.write(BININT1 + chr(obj))
  369. return
  370. if obj <= 0xffff:
  371. self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
  372. return
  373. # Next check for 4-byte signed ints:
  374. high_bits = obj >> 31 # note that Python shift sign-extends
  375. if high_bits == 0 or high_bits == -1:
  376. # All high bits are copies of bit 2**31, so the value
  377. # fits in a 4-byte signed int.
  378. self.write(BININT + pack("<i", obj))
  379. return
  380. # Text pickle, or int too big to fit in signed 4-byte format.
  381. self.write(INT + repr(obj) + '\n')
  382. dispatch[IntType] = save_int
  383. def save_long(self, obj, pack=struct.pack):
  384. if self.proto >= 2:
  385. bytes = encode_long(obj)
  386. n = len(bytes)
  387. if n < 256:
  388. self.write(LONG1 + chr(n) + bytes)
  389. else:
  390. self.write(LONG4 + pack("<i", n) + bytes)
  391. return
  392. self.write(LONG + repr(obj) + '\n')
  393. dispatch[LongType] = save_long
  394. def save_float(self, obj, pack=struct.pack):
  395. if self.bin:
  396. self.write(BINFLOAT + pack('>d', obj))
  397. else:
  398. self.write(FLOAT + repr(obj) + '\n')
  399. dispatch[FloatType] = save_float
  400. def save_string(self, obj, pack=struct.pack):
  401. if self.bin:
  402. n = len(obj)
  403. if n < 256:
  404. self.write(SHORT_BINSTRING + chr(n) + obj)
  405. else:
  406. self.write(BINSTRING + pack("<i", n) + obj)
  407. else:
  408. self.write(STRING + repr(obj) + '\n')
  409. self.memoize(obj)
  410. dispatch[StringType] = save_string
  411. def save_unicode(self, obj, pack=struct.pack):
  412. if self.bin:
  413. encoding = obj.encode('utf-8')
  414. n = len(encoding)
  415. self.write(BINUNICODE + pack("<i", n) + encoding)
  416. else:
  417. obj = obj.replace("\\", "\\u005c")
  418. obj = obj.replace("\n", "\\u000a")
  419. self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
  420. self.memoize(obj)
  421. dispatch[UnicodeType] = save_unicode
  422. if StringType is UnicodeType:
  423. # This is true for Jython
  424. def save_string(self, obj, pack=struct.pack):
  425. unicode = obj.isunicode()
  426. if self.bin:
  427. if unicode:
  428. obj = obj.encode("utf-8")
  429. l = len(obj)
  430. if l < 256 and not unicode:
  431. self.write(SHORT_BINSTRING + chr(l) + obj)
  432. else:
  433. s = pack("<i", l)
  434. if unicode:
  435. self.write(BINUNICODE + s + obj)
  436. else:
  437. self.write(BINSTRING + s + obj)
  438. else:
  439. if unicode:
  440. obj = obj.replace("\\", "\\u005c")
  441. obj = obj.replace("\n", "\\u000a")
  442. obj = obj.encode('raw-unicode-escape')
  443. self.write(UNICODE + obj + '\n')
  444. else:
  445. self.write(STRING + repr(obj) + '\n')
  446. self.memoize(obj)
  447. dispatch[StringType] = save_string
  448. def save_tuple(self, obj):
  449. write = self.write
  450. proto = self.proto
  451. n = len(obj)
  452. if n == 0:
  453. if proto:
  454. write(EMPTY_TUPLE)
  455. else:
  456. write(MARK + TUPLE)
  457. return
  458. save = self.save
  459. memo = self.memo
  460. if n <= 3 and proto >= 2:
  461. for element in obj:
  462. save(element)
  463. # Subtle. Same as in the big comment below.
  464. if id(obj) in memo:
  465. get = self.get(memo[id(obj)][0])
  466. write(POP * n + get)
  467. else:
  468. write(_tuplesize2code[n])
  469. self.memoize(obj)
  470. return
  471. # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
  472. # has more than 3 elements.
  473. write(MARK)
  474. for element in obj:
  475. save(element)
  476. if id(obj) in memo:
  477. # Subtle. d was not in memo when we entered save_tuple(), so
  478. # the process of saving the tuple's elements must have saved
  479. # the tuple itself: the tuple is recursive. The proper action
  480. # now is to throw away everything we put on the stack, and
  481. # simply GET the tuple (it's already constructed). This check
  482. # could have been done in the "for element" loop instead, but
  483. # recursive tuples are a rare thing.
  484. get = self.get(memo[id(obj)][0])
  485. if proto:
  486. write(POP_MARK + get)
  487. else: # proto 0 -- POP_MARK not available
  488. write(POP * (n+1) + get)
  489. return
  490. # No recursion.
  491. self.write(TUPLE)
  492. self.memoize(obj)
  493. dispatch[TupleType] = save_tuple
  494. # save_empty_tuple() isn't used by anything in Python 2.3. However, I
  495. # found a Pickler subclass in Zope3 that calls it, so it's not harmless
  496. # to remove it.
  497. def save_empty_tuple(self, obj):
  498. self.write(EMPTY_TUPLE)
  499. def save_list(self, obj):
  500. write = self.write
  501. if self.bin:
  502. write(EMPTY_LIST)
  503. else: # proto 0 -- can't use EMPTY_LIST
  504. write(MARK + LIST)
  505. self.memoize(obj)
  506. self._batch_appends(iter(obj))
  507. dispatch[ListType] = save_list
  508. # Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
  509. # out of synch, though.
  510. _BATCHSIZE = 1000
  511. def _batch_appends(self, items):
  512. # Helper to batch up APPENDS sequences
  513. save = self.save
  514. write = self.write
  515. if not self.bin:
  516. for x in items:
  517. save(x)
  518. write(APPEND)
  519. return
  520. r = xrange(self._BATCHSIZE)
  521. while items is not None:
  522. tmp = []
  523. for i in r:
  524. try:
  525. x = items.next()
  526. tmp.append(x)
  527. except StopIteration:
  528. items = None
  529. break
  530. n = len(tmp)
  531. if n > 1:
  532. write(MARK)
  533. for x in tmp:
  534. save(x)
  535. write(APPENDS)
  536. elif n:
  537. save(tmp[0])
  538. write(APPEND)
  539. # else tmp is empty, and we're done
  540. def save_dict(self, obj):
  541. write = self.write
  542. if self.bin:
  543. write(EMPTY_DICT)
  544. else: # proto 0 -- can't use EMPTY_DICT
  545. write(MARK + DICT)
  546. self.memoize(obj)
  547. self._batch_setitems(obj.iteritems())
  548. dispatch[DictionaryType] = save_dict
  549. if not PyStringMap is None:
  550. dispatch[PyStringMap] = save_dict
  551. def _batch_setitems(self, items):
  552. # Helper to batch up SETITEMS sequences; proto >= 1 only
  553. save = self.save
  554. write = self.write
  555. if not self.bin:
  556. for k, v in items:
  557. save(k)
  558. save(v)
  559. write(SETITEM)
  560. return
  561. r = xrange(self._BATCHSIZE)
  562. while items is not None:
  563. tmp = []
  564. for i in r:
  565. try:
  566. tmp.append(items.next())
  567. except StopIteration:
  568. items = None
  569. break
  570. n = len(tmp)
  571. if n > 1:
  572. write(MARK)
  573. for k, v in tmp:
  574. save(k)
  575. save(v)
  576. write(SETITEMS)
  577. elif n:
  578. k, v = tmp[0]
  579. save(k)
  580. save(v)
  581. write(SETITEM)
  582. # else tmp is empty, and we're done
  583. def save_inst(self, obj):
  584. cls = obj.__class__
  585. memo = self.memo
  586. write = self.write
  587. save = self.save
  588. if hasattr(obj, '__getinitargs__'):
  589. args = obj.__getinitargs__()
  590. len(args) # XXX Assert it's a sequence
  591. _keep_alive(args, memo)
  592. else:
  593. args = ()
  594. write(MARK)
  595. if self.bin:
  596. save(cls)
  597. for arg in args:
  598. save(arg)
  599. write(OBJ)
  600. else:
  601. for arg in args:
  602. save(arg)
  603. write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
  604. self.memoize(obj)
  605. try:
  606. getstate = obj.__getstate__
  607. except AttributeError:
  608. stuff = obj.__dict__
  609. else:
  610. stuff = getstate()
  611. _keep_alive(stuff, memo)
  612. save(stuff)
  613. write(BUILD)
  614. dispatch[InstanceType] = save_inst
  615. def save_global(self, obj, name=None, pack=struct.pack):
  616. write = self.write
  617. memo = self.memo
  618. if name is None:
  619. name = obj.__name__
  620. module = getattr(obj, "__module__", None)
  621. if module is None:
  622. module = whichmodule(obj, name)
  623. try:
  624. __import__(module)
  625. mod = sys.modules[module]
  626. klass = getattr(mod, name)
  627. except (ImportError, KeyError, AttributeError):
  628. raise PicklingError(
  629. "Can't pickle %r: it's not found as %s.%s" %
  630. (obj, module, name))
  631. else:
  632. if klass is not obj:
  633. raise PicklingError(
  634. "Can't pickle %r: it's not the same object as %s.%s" %
  635. (obj, module, name))
  636. if self.proto >= 2:
  637. code = _extension_registry.get((module, name))
  638. if code:
  639. assert code > 0
  640. if code <= 0xff:
  641. write(EXT1 + chr(code))
  642. elif code <= 0xffff:
  643. write("%c%c%c" % (EXT2, code&0xff, code>>8))
  644. else:
  645. write(EXT4 + pack("<i", code))
  646. return
  647. write(GLOBAL + module + '\n' + name + '\n')
  648. self.memoize(obj)
  649. dispatch[ClassType] = save_global
  650. dispatch[FunctionType] = save_global
  651. dispatch[BuiltinFunctionType] = save_global
  652. dispatch[TypeType] = save_global
  653. # Pickling helpers
  654. def _keep_alive(x, memo):
  655. """Keeps a reference to the object x in the memo.
  656. Because we remember objects by their id, we have
  657. to assure that possibly temporary objects are kept
  658. alive by referencing them.
  659. We store a reference at the id of the memo, which should
  660. normally not be used unless someone tries to deepcopy
  661. the memo itself...
  662. """
  663. try:
  664. memo[id(memo)].append(x)
  665. except KeyError:
  666. # aha, this is the first one :-)
  667. memo[id(memo)]=[x]
  668. # A cache for whichmodule(), mapping a function object to the name of
  669. # the module in which the function was found.
  670. classmap = {} # called classmap for backwards compatibility
  671. def whichmodule(func, funcname):
  672. """Figure out the module in which a function occurs.
  673. Search sys.modules for the module.
  674. Cache in classmap.
  675. Return a module name.
  676. If the function cannot be found, return "__main__".
  677. """
  678. # Python functions should always get an __module__ from their globals.
  679. mod = getattr(func, "__module__", None)
  680. if mod is not None:
  681. return mod
  682. if func in classmap:
  683. return classmap[func]
  684. for name, module in sys.modules.items():
  685. if module is None:
  686. continue # skip dummy package entries
  687. if name != '__main__' and getattr(module, funcname, None) is func:
  688. break
  689. else:
  690. name = '__main__'
  691. classmap[func] = name
  692. return name
  693. # Unpickling machinery
  694. class Unpickler:
  695. def __init__(self, file):
  696. """This takes a file-like object for reading a pickle data stream.
  697. The protocol version of the pickle is detected automatically, so no
  698. proto argument is needed.
  699. The file-like object must have two methods, a read() method that
  700. takes an integer argument, and a readline() method that requires no
  701. arguments. Both methods should return a string. Thus file-like
  702. object can be a file object opened for reading, a StringIO object,
  703. or any other custom object that meets this interface.
  704. """
  705. self.readline = file.readline
  706. self.read = file.read
  707. self.memo = {}
  708. def load(self):
  709. """Read a pickled object representation from the open file.
  710. Return the reconstituted object hierarchy specified in the file.
  711. """
  712. self.mark = object() # any new unique object
  713. self.stack = []
  714. self.append = self.stack.append
  715. read = self.read
  716. dispatch = self.dispatch
  717. try:
  718. while 1:
  719. key = read(1)
  720. dispatch[key](self)
  721. except _Stop, stopinst:
  722. return stopinst.value
  723. # Return largest index k such that self.stack[k] is self.mark.
  724. # If the stack doesn't contain a mark, eventually raises IndexError.
  725. # This could be sped by maintaining another stack, of indices at which
  726. # the mark appears. For that matter, the latter stack would suffice,
  727. # and we wouldn't need to push mark objects on self.stack at all.
  728. # Doing so is probably a good thing, though, since if the pickle is
  729. # corrupt (or hostile) we may get a clue from finding self.mark embedded
  730. # in unpickled objects.
  731. def marker(self):
  732. stack = self.stack
  733. mark = self.mark
  734. k = len(stack)-1
  735. while stack[k] is not mark: k = k-1
  736. return k
  737. dispatch = {}
  738. def load_eof(self):
  739. raise EOFError
  740. dispatch[''] = load_eof
  741. def load_proto(self):
  742. proto = ord(self.read(1))
  743. if not 0 <= proto <= 2:
  744. raise ValueError, "unsupported pickle protocol: %d" % proto
  745. dispatch[PROTO] = load_proto
  746. def load_persid(self):
  747. pid = self.readline()[:-1]
  748. self.append(self.persistent_load(pid))
  749. dispatch[PERSID] = load_persid
  750. def load_binpersid(self):
  751. pid = self.stack.pop()
  752. self.append(self.persistent_load(pid))
  753. dispatch[BINPERSID] = load_binpersid
  754. def load_none(self):
  755. self.append(None)
  756. dispatch[NONE] = load_none
  757. def load_false(self):
  758. self.append(False)
  759. dispatch[NEWFALSE] = load_false
  760. def load_true(self):
  761. self.append(True)
  762. dispatch[NEWTRUE] = load_true
  763. def load_int(self):
  764. data = self.readline()
  765. if data == FALSE[1:]:
  766. val = False
  767. elif data == TRUE[1:]:
  768. val = True
  769. else:
  770. try:
  771. val = int(data)
  772. except ValueError:
  773. val = long(data)
  774. self.append(val)
  775. dispatch[INT] = load_int
  776. def load_binint(self):
  777. self.append(mloads('i' + self.read(4)))
  778. dispatch[BININT] = load_binint
  779. def load_binint1(self):
  780. self.append(ord(self.read(1)))
  781. dispatch[BININT1] = load_binint1
  782. def load_binint2(self):
  783. self.append(mloads('i' + self.read(2) + '\000\000'))
  784. dispatch[BININT2] = load_binint2
  785. def load_long(self):
  786. self.append(long(self.readline()[:-1], 0))
  787. dispatch[LONG] = load_long
  788. def load_long1(self):
  789. n = ord(self.read(1))
  790. bytes = self.read(n)
  791. self.append(decode_long(bytes))
  792. dispatch[LONG1] = load_long1
  793. def load_long4(self):
  794. n = mloads('i' + self.read(4))
  795. bytes = self.read(n)
  796. self.append(decode_long(bytes))
  797. dispatch[LONG4] = load_long4
  798. def load_float(self):
  799. self.append(float(self.readline()[:-1]))
  800. dispatch[FLOAT] = load_float
  801. def load_binfloat(self, unpack=struct.unpack):
  802. self.append(unpack('>d', self.read(8))[0])
  803. dispatch[BINFLOAT] = load_binfloat
  804. def load_string(self):
  805. rep = self.readline()[:-1]
  806. for q in "\"'": # double or single quote
  807. if rep.startswith(q):
  808. if not rep.endswith(q):
  809. raise ValueError, "insecure string pickle"
  810. rep = rep[len(q):-len(q)]
  811. break
  812. else:
  813. raise ValueError, "insecure string pickle"
  814. self.append(rep.decode("string-escape"))
  815. dispatch[STRING] = load_string
  816. def load_binstring(self):
  817. len = mloads('i' + self.read(4))
  818. self.append(self.read(len))
  819. dispatch[BINSTRING] = load_binstring
  820. def load_unicode(self):
  821. self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
  822. dispatch[UNICODE] = load_unicode
  823. def load_binunicode(self):
  824. len = mloads('i' + self.read(4))
  825. self.append(unicode(self.read(len),'utf-8'))
  826. dispatch[BINUNICODE] = load_binunicode
  827. def load_short_binstring(self):
  828. len = ord(self.read(1))
  829. self.append(self.read(len))
  830. dispatch[SHORT_BINSTRING] = load_short_binstring
  831. def load_tuple(self):
  832. k = self.marker()
  833. self.stack[k:] = [tuple(self.stack[k+1:])]
  834. dispatch[TUPLE] = load_tuple
  835. def load_empty_tuple(self):
  836. self.stack.append(())
  837. dispatch[EMPTY_TUPLE] = load_empty_tuple
  838. def load_tuple1(self):
  839. self.stack[-1] = (self.stack[-1],)
  840. dispatch[TUPLE1] = load_tuple1
  841. def load_tuple2(self):
  842. self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
  843. dispatch[TUPLE2] = load_tuple2
  844. def load_tuple3(self):
  845. self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
  846. dispatch[TUPLE3] = load_tuple3
  847. def load_empty_list(self):
  848. self.stack.append([])
  849. dispatch[EMPTY_LIST] = load_empty_list
  850. def load_empty_dictionary(self):
  851. self.stack.append({})
  852. dispatch[EMPTY_DICT] = load_empty_dictionary
  853. def load_list(self):
  854. k = self.marker()
  855. self.stack[k:] = [self.stack[k+1:]]
  856. dispatch[LIST] = load_list
  857. def load_dict(self):
  858. k = self.marker()
  859. d = {}
  860. items = self.stack[k+1:]
  861. for i in range(0, len(items), 2):
  862. key = items[i]
  863. value = items[i+1]
  864. d[key] = value
  865. self.stack[k:] = [d]
  866. dispatch[DICT] = load_dict
  867. # INST and OBJ differ only in how they get a class object. It's not
  868. # only sensible to do the rest in a common routine, the two routines
  869. # previously diverged and grew different bugs.
  870. # klass is the class to instantiate, and k points to the topmost mark
  871. # object, following which are the arguments for klass.__init__.
  872. def _instantiate(self, klass, k):
  873. args = tuple(self.stack[k+1:])
  874. del self.stack[k:]
  875. instantiated = 0
  876. if (not args and
  877. type(klass) is ClassType and
  878. not hasattr(klass, "__getinitargs__")):
  879. try:
  880. value = _EmptyClass()
  881. value.__class__ = klass
  882. instantiated = 1
  883. except RuntimeError:
  884. # In restricted execution, assignment to inst.__class__ is
  885. # prohibited
  886. pass
  887. if not instantiated:
  888. try:
  889. value = klass(*args)
  890. except TypeError, err:
  891. raise TypeError, "in constructor for %s: %s" % (
  892. klass.__name__, str(err)), sys.exc_info()[2]
  893. self.append(value)
  894. def load_inst(self):
  895. module = self.readline()[:-1]
  896. name = self.readline()[:-1]
  897. klass = self.find_class(module, name)
  898. self._instantiate(klass, self.marker())
  899. dispatch[INST] = load_inst
  900. def load_obj(self):
  901. # Stack is ... markobject classobject arg1 arg2 ...
  902. k = self.marker()
  903. klass = self.stack.pop(k+1)
  904. self._instantiate(klass, k)
  905. dispatch[OBJ] = load_obj
  906. def load_newobj(self):
  907. args = self.stack.pop()
  908. cls = self.stack[-1]
  909. obj = cls.__new__(cls, *args)
  910. self.stack[-1] = obj
  911. dispatch[NEWOBJ] = load_newobj
  912. def load_global(self):
  913. module = self.readline()[:-1]
  914. name = self.readline()[:-1]
  915. klass = self.find_class(module, name)
  916. self.append(klass)
  917. dispatch[GLOBAL] = load_global
  918. def load_ext1(self):
  919. code = ord(self.read(1))
  920. self.get_extension(code)
  921. dispatch[EXT1] = load_ext1
  922. def load_ext2(self):
  923. code = mloads('i' + self.read(2) + '\000\000')
  924. self.get_extension(code)
  925. dispatch[EXT2] = load_ext2
  926. def load_ext4(self):
  927. code = mloads('i' + self.read(4))
  928. self.get_extension(code)
  929. dispatch[EXT4] = load_ext4
  930. def get_extension(self, code):
  931. nil = []
  932. obj = _extension_cache.get(code, nil)
  933. if obj is not nil:
  934. self.append(obj)
  935. return
  936. key = _inverted_registry.get(code)
  937. if not key:
  938. raise ValueError("unregistered extension code %d" % code)
  939. obj = self.find_class(*key)
  940. _extension_cache[code] = obj
  941. self.append(obj)
  942. def find_class(self, module, name):
  943. # Subclasses may override this
  944. __import__(module)
  945. mod = sys.modules[module]
  946. klass = getattr(mod, name)
  947. return klass
  948. def load_reduce(self):
  949. stack = self.stack
  950. args = stack.pop()
  951. func = stack[-1]
  952. value = func(*args)
  953. stack[-1] = value
  954. dispatch[REDUCE] = load_reduce
  955. def load_pop(self):
  956. del self.stack[-1]
  957. dispatch[POP] = load_pop
  958. def load_pop_mark(self):
  959. k = self.marker()
  960. del self.stack[k:]
  961. dispatch[POP_MARK] = load_pop_mark
  962. def load_dup(self):
  963. self.append(self.stack[-1])
  964. dispatch[DUP] = load_dup
  965. def load_get(self):
  966. self.append(self.memo[self.readline()[:-1]])
  967. dispatch[GET] = load_get
  968. def load_binget(self):
  969. i = ord(self.read(1))
  970. self.append(self.memo[repr(i)])
  971. dispatch[BINGET] = load_binget
  972. def load_long_binget(self):
  973. i = mloads('i' + self.read(4))
  974. self.append(self.memo[repr(i)])
  975. dispatch[LONG_BINGET] = load_long_binget
  976. def load_put(self):
  977. self.memo[self.readline()[:-1]] = self.stack[-1]
  978. dispatch[PUT] = load_put
  979. def load_binput(self):
  980. i = ord(self.read(1))
  981. self.memo[repr(i)] = self.stack[-1]
  982. dispatch[BINPUT] = load_binput
  983. def load_long_binput(self):
  984. i = mloads('i' + self.read(4))
  985. self.memo[repr(i)] = self.stack[-1]
  986. dispatch[LONG_BINPUT] = load_long_binput
  987. def load_append(self):
  988. stack = self.stack
  989. value = stack.pop()
  990. list = stack[-1]
  991. list.append(value)
  992. dispatch[APPEND] = load_append
  993. def load_appends(self):
  994. stack = self.stack
  995. mark = self.marker()
  996. list = stack[mark - 1]
  997. list.extend(stack[mark + 1:])
  998. del stack[mark:]
  999. dispatch[APPENDS] = load_appends
  1000. def load_setitem(self):
  1001. stack = self.stack
  1002. value = stack.pop()
  1003. key = stack.pop()
  1004. dict = stack[-1]
  1005. dict[key] = value
  1006. dispatch[SETITEM] = load_setitem
  1007. def load_setitems(self):
  1008. stack = self.stack
  1009. mark = self.marker()
  1010. dict = stack[mark - 1]
  1011. for i in range(mark + 1, len(stack), 2):
  1012. dict[stack[i]] = stack[i + 1]
  1013. del stack[mark:]
  1014. dispatch[SETITEMS] = load_setitems
  1015. def load_build(self):
  1016. stack = self.stack
  1017. state = stack.pop()
  1018. inst = stack[-1]
  1019. setstate = getattr(inst, "__setstate__", None)
  1020. if setstate:
  1021. setstate(state)
  1022. return
  1023. slotstate = None
  1024. if isinstance(state, tuple) and len(state) == 2:
  1025. state, slotstate = state
  1026. if state:
  1027. try:
  1028. d = inst.__dict__
  1029. try:
  1030. for k, v in state.iteritems():
  1031. d[intern(k)] = v
  1032. # keys in state don't have to be strings
  1033. # don't blow up, but don't go out of our way
  1034. except TypeError:
  1035. d.update(state)
  1036. except RuntimeError:
  1037. # XXX In restricted execution, the instance's __dict__
  1038. # is not accessible. Use the old way of unpickling
  1039. # the instance variables. This is a semantic
  1040. # difference when unpickling in restricted
  1041. # vs. unrestricted modes.
  1042. # Note, however, that cPickle has never tried to do the
  1043. # .update() business, and always uses
  1044. # PyObject_SetItem(inst.__dict__, key, value) in a
  1045. # loop over state.items().
  1046. for k, v in state.items():
  1047. setattr(inst, k, v)
  1048. if slotstate:
  1049. for k, v in slotstate.items():
  1050. setattr(inst, k, v)
  1051. dispatch[BUILD] = load_build
  1052. def load_mark(self):
  1053. self.append(self.mark)
  1054. dispatch[MARK] = load_mark
  1055. def load_stop(self):
  1056. value = self.stack.pop()
  1057. raise _Stop(value)
  1058. dispatch[STOP] = load_stop
  1059. # Helper class for load_inst/load_obj
  1060. class _EmptyClass:
  1061. pass
  1062. # Encode/decode longs in linear time.
  1063. import binascii as _binascii
  1064. def encode_long(x):
  1065. r"""Encode a long to a two's complement little-endian binary string.
  1066. Note that 0L is a special case, returning an empty string, to save a
  1067. byte in the LONG1 pickling context.
  1068. >>> encode_long(0L)
  1069. ''
  1070. >>> encode_long(255L)
  1071. '\xff\x00'
  1072. >>> encode_long(32767L)
  1073. '\xff\x7f'
  1074. >>> encode_long(-256L)
  1075. '\x00\xff'
  1076. >>> encode_long(-32768L)
  1077. '\x00\x80'
  1078. >>> encode_long(-128L)
  1079. '\x80'
  1080. >>> encode_long(127L)
  1081. '\x7f'
  1082. >>>
  1083. """
  1084. if x == 0:
  1085. return ''
  1086. if x > 0:
  1087. ashex = hex(x)
  1088. assert ashex.startswith("0x")
  1089. njunkchars = 2 + ashex.endswith('L')
  1090. nibbles = len(ashex) - njunkchars
  1091. if nibbles & 1:
  1092. # need an even # of nibbles for unhexlify
  1093. ashex = "0x0" + ashex[2:]
  1094. elif int(ashex[2], 16) >= 8:
  1095. # "looks negative", so need a byte of sign bits
  1096. ashex = "0x00" + ashex[2:]
  1097. else:
  1098. # Build the 256's-complement: (1L << nbytes) + x. The trick is
  1099. # to find the number of bytes in linear time (although that should
  1100. # really be a constant-time task).
  1101. ashex = hex(-x)
  1102. assert ashex.startswith("0x")
  1103. njunkchars = 2 + ashex.endswith('L')
  1104. nibbles = len(ashex) - njunkchars
  1105. if nibbles & 1:
  1106. # Extend to a full byte.
  1107. nibbles += 1
  1108. nbits = nibbles * 4
  1109. x += 1L << nbits
  1110. assert x > 0
  1111. ashex = hex(x)
  1112. njunkchars = 2 + ashex.endswith('L')
  1113. newnibbles = len(ashex) - njunkchars
  1114. if newnibbles < nibbles:
  1115. ashex = "0x" + "0" * (nibbles - newnibbles) + ashex[2:]
  1116. if int(ashex[2], 16) < 8:
  1117. # "looks positive", so need a byte of sign bits
  1118. ashex = "0xff" + ashex[2:]
  1119. if ashex.endswith('L'):
  1120. ashex = ashex[2:-1]
  1121. else:
  1122. ashex = ashex[2:]
  1123. assert len(ashex) & 1 == 0, (x, ashex)
  1124. binary = _binascii.unhexlify(ashex)
  1125. return binary[::-1]
  1126. def decode_long(data):
  1127. r"""Decode a long from a two's complement little-endian binary string.
  1128. >>> decode_long('')
  1129. 0L
  1130. >>> decode_long("\xff\x00")
  1131. 255L
  1132. >>> decode_long("\xff\x7f")
  1133. 32767L
  1134. >>> decode_long("\x00\xff")
  1135. -256L
  1136. >>> decode_long("\x00\x80")
  1137. -32768L
  1138. >>> decode_long("\x80")
  1139. -128L
  1140. >>> decode_long("\x7f")
  1141. 127L
  1142. """
  1143. nbytes = len(data)
  1144. if nbytes == 0:
  1145. return 0L
  1146. ashex = _binascii.hexlify(data[::-1])
  1147. n = long(ashex, 16) # quadratic time before Python 2.3; linear now
  1148. if data[-1] >= '\x80':
  1149. n -= 1L << (nbytes * 8)
  1150. return n
  1151. # Shorthands
  1152. try:
  1153. from cStringIO import StringIO
  1154. except ImportError:
  1155. from StringIO import StringIO
  1156. def dump(obj, file, protocol=None):
  1157. Pickler(file, protocol).dump(obj)
  1158. def dumps(obj, protocol=None):
  1159. file = StringIO()
  1160. Pickler(file, protocol).dump(obj)
  1161. return file.getvalue()
  1162. def load(file):
  1163. return Unpickler(file).load()
  1164. def loads(str):
  1165. file = StringIO(str)
  1166. return Unpickler(file).load()
  1167. # Doctest
  1168. def _test():
  1169. import doctest
  1170. return doctest.testmod()
  1171. if __name__ == "__main__":
  1172. _test()