pickle.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. """Create portable serialized representations of Python objects.
  2. See module copyreg for a mechanism for registering custom picklers.
  3. See module pickletools source for extensive comments.
  4. Classes:
  5. Pickler
  6. Unpickler
  7. Functions:
  8. dump(object, file)
  9. dumps(object) -> string
  10. load(file) -> object
  11. loads(string) -> object
  12. Misc variables:
  13. __version__
  14. format_version
  15. compatible_formats
  16. """
  17. from types import FunctionType
  18. from copyreg import dispatch_table
  19. from copyreg import _extension_registry, _inverted_registry, _extension_cache
  20. from itertools import islice
  21. from functools import partial
  22. import sys
  23. from sys import maxsize
  24. from struct import pack, unpack
  25. import re
  26. import io
  27. import codecs
  28. import _compat_pickle
  29. __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
  30. "Unpickler", "dump", "dumps", "load", "loads"]
  31. # Shortcut for use in isinstance testing
  32. bytes_types = (bytes, bytearray)
  33. # These are purely informational; no code uses these.
  34. format_version = "4.0" # File format version we write
  35. compatible_formats = ["1.0", # Original protocol 0
  36. "1.1", # Protocol 0 with INST added
  37. "1.2", # Original protocol 1
  38. "1.3", # Protocol 1 with BINFLOAT added
  39. "2.0", # Protocol 2
  40. "3.0", # Protocol 3
  41. "4.0", # Protocol 4
  42. ] # Old format versions we can read
  43. # This is the highest protocol number we know how to read.
  44. HIGHEST_PROTOCOL = 4
  45. # The protocol we write by default. May be less than HIGHEST_PROTOCOL.
  46. # We intentionally write a protocol that Python 2.x cannot read;
  47. # there are too many issues with that.
  48. DEFAULT_PROTOCOL = 3
  49. class PickleError(Exception):
  50. """A common base class for the other pickling exceptions."""
  51. pass
  52. class PicklingError(PickleError):
  53. """This exception is raised when an unpicklable object is passed to the
  54. dump() method.
  55. """
  56. pass
  57. class UnpicklingError(PickleError):
  58. """This exception is raised when there is a problem unpickling an object,
  59. such as a security violation.
  60. Note that other exceptions may also be raised during unpickling, including
  61. (but not necessarily limited to) AttributeError, EOFError, ImportError,
  62. and IndexError.
  63. """
  64. pass
  65. # An instance of _Stop is raised by Unpickler.load_stop() in response to
  66. # the STOP opcode, passing the object that is the result of unpickling.
  67. class _Stop(Exception):
  68. def __init__(self, value):
  69. self.value = value
  70. # Jython has PyStringMap; it's a dict subclass with string keys
  71. try:
  72. from org.python.core import PyStringMap
  73. except ImportError:
  74. PyStringMap = None
  75. # Pickle opcodes. See pickletools.py for extensive docs. The listing
  76. # here is in kind-of alphabetical order of 1-character pickle code.
  77. # pickletools groups them by purpose.
  78. MARK = b'(' # push special markobject on stack
  79. STOP = b'.' # every pickle ends with STOP
  80. POP = b'0' # discard topmost stack item
  81. POP_MARK = b'1' # discard stack top through topmost markobject
  82. DUP = b'2' # duplicate top stack item
  83. FLOAT = b'F' # push float object; decimal string argument
  84. INT = b'I' # push integer or bool; decimal string argument
  85. BININT = b'J' # push four-byte signed int
  86. BININT1 = b'K' # push 1-byte unsigned int
  87. LONG = b'L' # push long; decimal string argument
  88. BININT2 = b'M' # push 2-byte unsigned int
  89. NONE = b'N' # push None
  90. PERSID = b'P' # push persistent object; id is taken from string arg
  91. BINPERSID = b'Q' # " " " ; " " " " stack
  92. REDUCE = b'R' # apply callable to argtuple, both on stack
  93. STRING = b'S' # push string; NL-terminated string argument
  94. BINSTRING = b'T' # push string; counted binary string argument
  95. SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes
  96. UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument
  97. BINUNICODE = b'X' # " " " ; counted UTF-8 string argument
  98. APPEND = b'a' # append stack top to list below it
  99. BUILD = b'b' # call __setstate__ or __dict__.update()
  100. GLOBAL = b'c' # push self.find_class(modname, name); 2 string args
  101. DICT = b'd' # build a dict from stack items
  102. EMPTY_DICT = b'}' # push empty dict
  103. APPENDS = b'e' # extend list on stack by topmost stack slice
  104. GET = b'g' # push item from memo on stack; index is string arg
  105. BINGET = b'h' # " " " " " " ; " " 1-byte arg
  106. INST = b'i' # build & push class instance
  107. LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg
  108. LIST = b'l' # build list from topmost stack items
  109. EMPTY_LIST = b']' # push empty list
  110. OBJ = b'o' # build & push class instance
  111. PUT = b'p' # store stack top in memo; index is string arg
  112. BINPUT = b'q' # " " " " " ; " " 1-byte arg
  113. LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg
  114. SETITEM = b's' # add key+value pair to dict
  115. TUPLE = b't' # build tuple from topmost stack items
  116. EMPTY_TUPLE = b')' # push empty tuple
  117. SETITEMS = b'u' # modify dict by adding topmost key+value pairs
  118. BINFLOAT = b'G' # push float; arg is 8-byte float encoding
  119. TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py
  120. FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py
  121. # Protocol 2
  122. PROTO = b'\x80' # identify pickle protocol
  123. NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple
  124. EXT1 = b'\x82' # push object from extension registry; 1-byte index
  125. EXT2 = b'\x83' # ditto, but 2-byte index
  126. EXT4 = b'\x84' # ditto, but 4-byte index
  127. TUPLE1 = b'\x85' # build 1-tuple from stack top
  128. TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items
  129. TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items
  130. NEWTRUE = b'\x88' # push True
  131. NEWFALSE = b'\x89' # push False
  132. LONG1 = b'\x8a' # push long from < 256 bytes
  133. LONG4 = b'\x8b' # push really big long
  134. _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3]
  135. # Protocol 3 (Python 3.x)
  136. BINBYTES = b'B' # push bytes; counted binary string argument
  137. SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes
  138. # Protocol 4
  139. SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes
  140. BINUNICODE8 = b'\x8d' # push very long string
  141. BINBYTES8 = b'\x8e' # push very long bytes string
  142. EMPTY_SET = b'\x8f' # push empty set on the stack
  143. ADDITEMS = b'\x90' # modify set by adding topmost stack items
  144. FROZENSET = b'\x91' # build frozenset from topmost stack items
  145. NEWOBJ_EX = b'\x92' # like NEWOBJ but work with keyword only arguments
  146. STACK_GLOBAL = b'\x93' # same as GLOBAL but using names on the stacks
  147. MEMOIZE = b'\x94' # store top of the stack in memo
  148. FRAME = b'\x95' # indicate the beginning of a new frame
  149. __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)])
  150. class _Framer:
  151. _FRAME_SIZE_MIN = 4
  152. _FRAME_SIZE_TARGET = 64 * 1024
  153. def __init__(self, file_write):
  154. self.file_write = file_write
  155. self.current_frame = None
  156. def start_framing(self):
  157. self.current_frame = io.BytesIO()
  158. def end_framing(self):
  159. if self.current_frame and self.current_frame.tell() > 0:
  160. self.commit_frame(force=True)
  161. self.current_frame = None
  162. def commit_frame(self, force=False):
  163. if self.current_frame:
  164. f = self.current_frame
  165. if f.tell() >= self._FRAME_SIZE_TARGET or force:
  166. data = f.getbuffer()
  167. write = self.file_write
  168. if len(data) >= self._FRAME_SIZE_MIN:
  169. # Issue a single call to the write method of the underlying
  170. # file object for the frame opcode with the size of the
  171. # frame. The concatenation is expected to be less expensive
  172. # than issuing an additional call to write.
  173. write(FRAME + pack("<Q", len(data)))
  174. # Issue a separate call to write to append the frame
  175. # contents without concatenation to the above to avoid a
  176. # memory copy.
  177. write(data)
  178. # Start the new frame with a new io.BytesIO instance so that
  179. # the file object can have delayed access to the previous frame
  180. # contents via an unreleased memoryview of the previous
  181. # io.BytesIO instance.
  182. self.current_frame = io.BytesIO()
  183. def write(self, data):
  184. if self.current_frame:
  185. return self.current_frame.write(data)
  186. else:
  187. return self.file_write(data)
  188. def write_large_bytes(self, header, payload):
  189. write = self.file_write
  190. if self.current_frame:
  191. # Terminate the current frame and flush it to the file.
  192. self.commit_frame(force=True)
  193. # Perform direct write of the header and payload of the large binary
  194. # object. Be careful not to concatenate the header and the payload
  195. # prior to calling 'write' as we do not want to allocate a large
  196. # temporary bytes object.
  197. # We intentionally do not insert a protocol 4 frame opcode to make
  198. # it possible to optimize file.read calls in the loader.
  199. write(header)
  200. write(payload)
  201. class _Unframer:
  202. def __init__(self, file_read, file_readline, file_tell=None):
  203. self.file_read = file_read
  204. self.file_readline = file_readline
  205. self.current_frame = None
  206. def read(self, n):
  207. if self.current_frame:
  208. data = self.current_frame.read(n)
  209. if not data and n != 0:
  210. self.current_frame = None
  211. return self.file_read(n)
  212. if len(data) < n:
  213. raise UnpicklingError(
  214. "pickle exhausted before end of frame")
  215. return data
  216. else:
  217. return self.file_read(n)
  218. def readline(self):
  219. if self.current_frame:
  220. data = self.current_frame.readline()
  221. if not data:
  222. self.current_frame = None
  223. return self.file_readline()
  224. if data[-1] != b'\n'[0]:
  225. raise UnpicklingError(
  226. "pickle exhausted before end of frame")
  227. return data
  228. else:
  229. return self.file_readline()
  230. def load_frame(self, frame_size):
  231. if self.current_frame and self.current_frame.read() != b'':
  232. raise UnpicklingError(
  233. "beginning of a new frame before end of current frame")
  234. self.current_frame = io.BytesIO(self.file_read(frame_size))
  235. # Tools used for pickling.
  236. def _getattribute(obj, name):
  237. for subpath in name.split('.'):
  238. if subpath == '<locals>':
  239. raise AttributeError("Can't get local attribute {!r} on {!r}"
  240. .format(name, obj))
  241. try:
  242. parent = obj
  243. obj = getattr(obj, subpath)
  244. except AttributeError:
  245. raise AttributeError("Can't get attribute {!r} on {!r}"
  246. .format(name, obj)) from None
  247. return obj, parent
  248. def whichmodule(obj, name):
  249. """Find the module an object belong to."""
  250. module_name = getattr(obj, '__module__', None)
  251. if module_name is not None:
  252. return module_name
  253. # Protect the iteration by using a list copy of sys.modules against dynamic
  254. # modules that trigger imports of other modules upon calls to getattr.
  255. for module_name, module in list(sys.modules.items()):
  256. if module_name == '__main__' or module is None:
  257. continue
  258. try:
  259. if _getattribute(module, name)[0] is obj:
  260. return module_name
  261. except AttributeError:
  262. pass
  263. return '__main__'
  264. def encode_long(x):
  265. r"""Encode a long to a two's complement little-endian binary string.
  266. Note that 0 is a special case, returning an empty string, to save a
  267. byte in the LONG1 pickling context.
  268. >>> encode_long(0)
  269. b''
  270. >>> encode_long(255)
  271. b'\xff\x00'
  272. >>> encode_long(32767)
  273. b'\xff\x7f'
  274. >>> encode_long(-256)
  275. b'\x00\xff'
  276. >>> encode_long(-32768)
  277. b'\x00\x80'
  278. >>> encode_long(-128)
  279. b'\x80'
  280. >>> encode_long(127)
  281. b'\x7f'
  282. >>>
  283. """
  284. if x == 0:
  285. return b''
  286. nbytes = (x.bit_length() >> 3) + 1
  287. result = x.to_bytes(nbytes, byteorder='little', signed=True)
  288. if x < 0 and nbytes > 1:
  289. if result[-1] == 0xff and (result[-2] & 0x80) != 0:
  290. result = result[:-1]
  291. return result
  292. def decode_long(data):
  293. r"""Decode a long from a two's complement little-endian binary string.
  294. >>> decode_long(b'')
  295. 0
  296. >>> decode_long(b"\xff\x00")
  297. 255
  298. >>> decode_long(b"\xff\x7f")
  299. 32767
  300. >>> decode_long(b"\x00\xff")
  301. -256
  302. >>> decode_long(b"\x00\x80")
  303. -32768
  304. >>> decode_long(b"\x80")
  305. -128
  306. >>> decode_long(b"\x7f")
  307. 127
  308. """
  309. return int.from_bytes(data, byteorder='little', signed=True)
  310. # Pickling machinery
  311. class _Pickler:
  312. def __init__(self, file, protocol=None, *, fix_imports=True):
  313. """This takes a binary file for writing a pickle data stream.
  314. The optional *protocol* argument tells the pickler to use the
  315. given protocol; supported protocols are 0, 1, 2, 3 and 4. The
  316. default protocol is 3; a backward-incompatible protocol designed
  317. for Python 3.
  318. Specifying a negative protocol version selects the highest
  319. protocol version supported. The higher the protocol used, the
  320. more recent the version of Python needed to read the pickle
  321. produced.
  322. The *file* argument must have a write() method that accepts a
  323. single bytes argument. It can thus be a file object opened for
  324. binary writing, an io.BytesIO instance, or any other custom
  325. object that meets this interface.
  326. If *fix_imports* is True and *protocol* is less than 3, pickle
  327. will try to map the new Python 3 names to the old module names
  328. used in Python 2, so that the pickle data stream is readable
  329. with Python 2.
  330. """
  331. if protocol is None:
  332. protocol = DEFAULT_PROTOCOL
  333. if protocol < 0:
  334. protocol = HIGHEST_PROTOCOL
  335. elif not 0 <= protocol <= HIGHEST_PROTOCOL:
  336. raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL)
  337. try:
  338. self._file_write = file.write
  339. except AttributeError:
  340. raise TypeError("file must have a 'write' attribute")
  341. self.framer = _Framer(self._file_write)
  342. self.write = self.framer.write
  343. self._write_large_bytes = self.framer.write_large_bytes
  344. self.memo = {}
  345. self.proto = int(protocol)
  346. self.bin = protocol >= 1
  347. self.fast = 0
  348. self.fix_imports = fix_imports and protocol < 3
  349. def clear_memo(self):
  350. """Clears the pickler's "memo".
  351. The memo is the data structure that remembers which objects the
  352. pickler has already seen, so that shared or recursive objects
  353. are pickled by reference and not by value. This method is
  354. useful when re-using picklers.
  355. """
  356. self.memo.clear()
  357. def dump(self, obj):
  358. """Write a pickled representation of obj to the open file."""
  359. # Check whether Pickler was initialized correctly. This is
  360. # only needed to mimic the behavior of _pickle.Pickler.dump().
  361. if not hasattr(self, "_file_write"):
  362. raise PicklingError("Pickler.__init__() was not called by "
  363. "%s.__init__()" % (self.__class__.__name__,))
  364. if self.proto >= 2:
  365. self.write(PROTO + pack("<B", self.proto))
  366. if self.proto >= 4:
  367. self.framer.start_framing()
  368. self.save(obj)
  369. self.write(STOP)
  370. self.framer.end_framing()
  371. def memoize(self, obj):
  372. """Store an object in the memo."""
  373. # The Pickler memo is a dictionary mapping object ids to 2-tuples
  374. # that contain the Unpickler memo key and the object being memoized.
  375. # The memo key is written to the pickle and will become
  376. # the key in the Unpickler's memo. The object is stored in the
  377. # Pickler memo so that transient objects are kept alive during
  378. # pickling.
  379. # The use of the Unpickler memo length as the memo key is just a
  380. # convention. The only requirement is that the memo values be unique.
  381. # But there appears no advantage to any other scheme, and this
  382. # scheme allows the Unpickler memo to be implemented as a plain (but
  383. # growable) array, indexed by memo key.
  384. if self.fast:
  385. return
  386. assert id(obj) not in self.memo
  387. idx = len(self.memo)
  388. self.write(self.put(idx))
  389. self.memo[id(obj)] = idx, obj
  390. # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i.
  391. def put(self, idx):
  392. if self.proto >= 4:
  393. return MEMOIZE
  394. elif self.bin:
  395. if idx < 256:
  396. return BINPUT + pack("<B", idx)
  397. else:
  398. return LONG_BINPUT + pack("<I", idx)
  399. else:
  400. return PUT + repr(idx).encode("ascii") + b'\n'
  401. # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i.
  402. def get(self, i):
  403. if self.bin:
  404. if i < 256:
  405. return BINGET + pack("<B", i)
  406. else:
  407. return LONG_BINGET + pack("<I", i)
  408. return GET + repr(i).encode("ascii") + b'\n'
  409. def save(self, obj, save_persistent_id=True):
  410. self.framer.commit_frame()
  411. # Check for persistent id (defined by a subclass)
  412. pid = self.persistent_id(obj)
  413. if pid is not None and save_persistent_id:
  414. self.save_pers(pid)
  415. return
  416. # Check the memo
  417. x = self.memo.get(id(obj))
  418. if x is not None:
  419. self.write(self.get(x[0]))
  420. return
  421. # Check the type dispatch table
  422. t = type(obj)
  423. f = self.dispatch.get(t)
  424. if f is not None:
  425. f(self, obj) # Call unbound method with explicit self
  426. return
  427. # Check private dispatch table if any, or else copyreg.dispatch_table
  428. reduce = getattr(self, 'dispatch_table', dispatch_table).get(t)
  429. if reduce is not None:
  430. rv = reduce(obj)
  431. else:
  432. # Check for a class with a custom metaclass; treat as regular class
  433. try:
  434. issc = issubclass(t, type)
  435. except TypeError: # t is not a class (old Boost; see SF #502085)
  436. issc = False
  437. if issc:
  438. self.save_global(obj)
  439. return
  440. # Check for a __reduce_ex__ method, fall back to __reduce__
  441. reduce = getattr(obj, "__reduce_ex__", None)
  442. if reduce is not None:
  443. rv = reduce(self.proto)
  444. else:
  445. reduce = getattr(obj, "__reduce__", None)
  446. if reduce is not None:
  447. rv = reduce()
  448. else:
  449. raise PicklingError("Can't pickle %r object: %r" %
  450. (t.__name__, obj))
  451. # Check for string returned by reduce(), meaning "save as global"
  452. if isinstance(rv, str):
  453. self.save_global(obj, rv)
  454. return
  455. # Assert that reduce() returned a tuple
  456. if not isinstance(rv, tuple):
  457. raise PicklingError("%s must return string or tuple" % reduce)
  458. # Assert that it returned an appropriately sized tuple
  459. l = len(rv)
  460. if not (2 <= l <= 5):
  461. raise PicklingError("Tuple returned by %s must have "
  462. "two to five elements" % reduce)
  463. # Save the reduce() output and finally memoize the object
  464. self.save_reduce(obj=obj, *rv)
  465. def persistent_id(self, obj):
  466. # This exists so a subclass can override it
  467. return None
  468. def save_pers(self, pid):
  469. # Save a persistent id reference
  470. if self.bin:
  471. self.save(pid, save_persistent_id=False)
  472. self.write(BINPERSID)
  473. else:
  474. try:
  475. self.write(PERSID + str(pid).encode("ascii") + b'\n')
  476. except UnicodeEncodeError:
  477. raise PicklingError(
  478. "persistent IDs in protocol 0 must be ASCII strings")
  479. def save_reduce(self, func, args, state=None, listitems=None,
  480. dictitems=None, obj=None):
  481. # This API is called by some subclasses
  482. if not isinstance(args, tuple):
  483. raise PicklingError("args from save_reduce() must be a tuple")
  484. if not callable(func):
  485. raise PicklingError("func from save_reduce() must be callable")
  486. save = self.save
  487. write = self.write
  488. func_name = getattr(func, "__name__", "")
  489. if self.proto >= 2 and func_name == "__newobj_ex__":
  490. cls, args, kwargs = args
  491. if not hasattr(cls, "__new__"):
  492. raise PicklingError("args[0] from {} args has no __new__"
  493. .format(func_name))
  494. if obj is not None and cls is not obj.__class__:
  495. raise PicklingError("args[0] from {} args has the wrong class"
  496. .format(func_name))
  497. if self.proto >= 4:
  498. save(cls)
  499. save(args)
  500. save(kwargs)
  501. write(NEWOBJ_EX)
  502. else:
  503. func = partial(cls.__new__, cls, *args, **kwargs)
  504. save(func)
  505. save(())
  506. write(REDUCE)
  507. elif self.proto >= 2 and func_name == "__newobj__":
  508. # A __reduce__ implementation can direct protocol 2 or newer to
  509. # use the more efficient NEWOBJ opcode, while still
  510. # allowing protocol 0 and 1 to work normally. For this to
  511. # work, the function returned by __reduce__ should be
  512. # called __newobj__, and its first argument should be a
  513. # class. The implementation for __newobj__
  514. # should be as follows, although pickle has no way to
  515. # verify this:
  516. #
  517. # def __newobj__(cls, *args):
  518. # return cls.__new__(cls, *args)
  519. #
  520. # Protocols 0 and 1 will pickle a reference to __newobj__,
  521. # while protocol 2 (and above) will pickle a reference to
  522. # cls, the remaining args tuple, and the NEWOBJ code,
  523. # which calls cls.__new__(cls, *args) at unpickling time
  524. # (see load_newobj below). If __reduce__ returns a
  525. # three-tuple, the state from the third tuple item will be
  526. # pickled regardless of the protocol, calling __setstate__
  527. # at unpickling time (see load_build below).
  528. #
  529. # Note that no standard __newobj__ implementation exists;
  530. # you have to provide your own. This is to enforce
  531. # compatibility with Python 2.2 (pickles written using
  532. # protocol 0 or 1 in Python 2.3 should be unpicklable by
  533. # Python 2.2).
  534. cls = args[0]
  535. if not hasattr(cls, "__new__"):
  536. raise PicklingError(
  537. "args[0] from __newobj__ args has no __new__")
  538. if obj is not None and cls is not obj.__class__:
  539. raise PicklingError(
  540. "args[0] from __newobj__ args has the wrong class")
  541. args = args[1:]
  542. save(cls)
  543. save(args)
  544. write(NEWOBJ)
  545. else:
  546. save(func)
  547. save(args)
  548. write(REDUCE)
  549. if obj is not None:
  550. # If the object is already in the memo, this means it is
  551. # recursive. In this case, throw away everything we put on the
  552. # stack, and fetch the object back from the memo.
  553. if id(obj) in self.memo:
  554. write(POP + self.get(self.memo[id(obj)][0]))
  555. else:
  556. self.memoize(obj)
  557. # More new special cases (that work with older protocols as
  558. # well): when __reduce__ returns a tuple with 4 or 5 items,
  559. # the 4th and 5th item should be iterators that provide list
  560. # items and dict items (as (key, value) tuples), or None.
  561. if listitems is not None:
  562. self._batch_appends(listitems)
  563. if dictitems is not None:
  564. self._batch_setitems(dictitems)
  565. if state is not None:
  566. save(state)
  567. write(BUILD)
  568. # Methods below this point are dispatched through the dispatch table
  569. dispatch = {}
  570. def save_none(self, obj):
  571. self.write(NONE)
  572. dispatch[type(None)] = save_none
  573. def save_bool(self, obj):
  574. if self.proto >= 2:
  575. self.write(NEWTRUE if obj else NEWFALSE)
  576. else:
  577. self.write(TRUE if obj else FALSE)
  578. dispatch[bool] = save_bool
  579. def save_long(self, obj):
  580. if self.bin:
  581. # If the int is small enough to fit in a signed 4-byte 2's-comp
  582. # format, we can store it more efficiently than the general
  583. # case.
  584. # First one- and two-byte unsigned ints:
  585. if obj >= 0:
  586. if obj <= 0xff:
  587. self.write(BININT1 + pack("<B", obj))
  588. return
  589. if obj <= 0xffff:
  590. self.write(BININT2 + pack("<H", obj))
  591. return
  592. # Next check for 4-byte signed ints:
  593. if -0x80000000 <= obj <= 0x7fffffff:
  594. self.write(BININT + pack("<i", obj))
  595. return
  596. if self.proto >= 2:
  597. encoded = encode_long(obj)
  598. n = len(encoded)
  599. if n < 256:
  600. self.write(LONG1 + pack("<B", n) + encoded)
  601. else:
  602. self.write(LONG4 + pack("<i", n) + encoded)
  603. return
  604. if -0x80000000 <= obj <= 0x7fffffff:
  605. self.write(INT + repr(obj).encode("ascii") + b'\n')
  606. else:
  607. self.write(LONG + repr(obj).encode("ascii") + b'L\n')
  608. dispatch[int] = save_long
  609. def save_float(self, obj):
  610. if self.bin:
  611. self.write(BINFLOAT + pack('>d', obj))
  612. else:
  613. self.write(FLOAT + repr(obj).encode("ascii") + b'\n')
  614. dispatch[float] = save_float
  615. def save_bytes(self, obj):
  616. if self.proto < 3:
  617. if not obj: # bytes object is empty
  618. self.save_reduce(bytes, (), obj=obj)
  619. else:
  620. self.save_reduce(codecs.encode,
  621. (str(obj, 'latin1'), 'latin1'), obj=obj)
  622. return
  623. n = len(obj)
  624. if n <= 0xff:
  625. self.write(SHORT_BINBYTES + pack("<B", n) + obj)
  626. elif n > 0xffffffff and self.proto >= 4:
  627. self._write_large_bytes(BINBYTES8 + pack("<Q", n), obj)
  628. elif n >= self.framer._FRAME_SIZE_TARGET:
  629. self._write_large_bytes(BINBYTES + pack("<I", n), obj)
  630. else:
  631. self.write(BINBYTES + pack("<I", n) + obj)
  632. self.memoize(obj)
  633. dispatch[bytes] = save_bytes
  634. def save_str(self, obj):
  635. if self.bin:
  636. encoded = obj.encode('utf-8', 'surrogatepass')
  637. n = len(encoded)
  638. if n <= 0xff and self.proto >= 4:
  639. self.write(SHORT_BINUNICODE + pack("<B", n) + encoded)
  640. elif n > 0xffffffff and self.proto >= 4:
  641. self._write_large_bytes(BINUNICODE8 + pack("<Q", n), encoded)
  642. elif n >= self.framer._FRAME_SIZE_TARGET:
  643. self._write_large_bytes(BINUNICODE + pack("<I", n), encoded)
  644. else:
  645. self.write(BINUNICODE + pack("<I", n) + encoded)
  646. else:
  647. obj = obj.replace("\\", "\\u005c")
  648. obj = obj.replace("\0", "\\u0000")
  649. obj = obj.replace("\n", "\\u000a")
  650. obj = obj.replace("\r", "\\u000d")
  651. obj = obj.replace("\x1a", "\\u001a") # EOF on DOS
  652. self.write(UNICODE + obj.encode('raw-unicode-escape') +
  653. b'\n')
  654. self.memoize(obj)
  655. dispatch[str] = save_str
  656. def save_tuple(self, obj):
  657. if not obj: # tuple is empty
  658. if self.bin:
  659. self.write(EMPTY_TUPLE)
  660. else:
  661. self.write(MARK + TUPLE)
  662. return
  663. n = len(obj)
  664. save = self.save
  665. memo = self.memo
  666. if n <= 3 and self.proto >= 2:
  667. for element in obj:
  668. save(element)
  669. # Subtle. Same as in the big comment below.
  670. if id(obj) in memo:
  671. get = self.get(memo[id(obj)][0])
  672. self.write(POP * n + get)
  673. else:
  674. self.write(_tuplesize2code[n])
  675. self.memoize(obj)
  676. return
  677. # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple
  678. # has more than 3 elements.
  679. write = self.write
  680. write(MARK)
  681. for element in obj:
  682. save(element)
  683. if id(obj) in memo:
  684. # Subtle. d was not in memo when we entered save_tuple(), so
  685. # the process of saving the tuple's elements must have saved
  686. # the tuple itself: the tuple is recursive. The proper action
  687. # now is to throw away everything we put on the stack, and
  688. # simply GET the tuple (it's already constructed). This check
  689. # could have been done in the "for element" loop instead, but
  690. # recursive tuples are a rare thing.
  691. get = self.get(memo[id(obj)][0])
  692. if self.bin:
  693. write(POP_MARK + get)
  694. else: # proto 0 -- POP_MARK not available
  695. write(POP * (n+1) + get)
  696. return
  697. # No recursion.
  698. write(TUPLE)
  699. self.memoize(obj)
  700. dispatch[tuple] = save_tuple
  701. def save_list(self, obj):
  702. if self.bin:
  703. self.write(EMPTY_LIST)
  704. else: # proto 0 -- can't use EMPTY_LIST
  705. self.write(MARK + LIST)
  706. self.memoize(obj)
  707. self._batch_appends(obj)
  708. dispatch[list] = save_list
  709. _BATCHSIZE = 1000
  710. def _batch_appends(self, items):
  711. # Helper to batch up APPENDS sequences
  712. save = self.save
  713. write = self.write
  714. if not self.bin:
  715. for x in items:
  716. save(x)
  717. write(APPEND)
  718. return
  719. it = iter(items)
  720. while True:
  721. tmp = list(islice(it, self._BATCHSIZE))
  722. n = len(tmp)
  723. if n > 1:
  724. write(MARK)
  725. for x in tmp:
  726. save(x)
  727. write(APPENDS)
  728. elif n:
  729. save(tmp[0])
  730. write(APPEND)
  731. # else tmp is empty, and we're done
  732. if n < self._BATCHSIZE:
  733. return
  734. def save_dict(self, obj):
  735. if self.bin:
  736. self.write(EMPTY_DICT)
  737. else: # proto 0 -- can't use EMPTY_DICT
  738. self.write(MARK + DICT)
  739. self.memoize(obj)
  740. self._batch_setitems(obj.items())
  741. dispatch[dict] = save_dict
  742. if PyStringMap is not None:
  743. dispatch[PyStringMap] = save_dict
  744. def _batch_setitems(self, items):
  745. # Helper to batch up SETITEMS sequences; proto >= 1 only
  746. save = self.save
  747. write = self.write
  748. if not self.bin:
  749. for k, v in items:
  750. save(k)
  751. save(v)
  752. write(SETITEM)
  753. return
  754. it = iter(items)
  755. while True:
  756. tmp = list(islice(it, self._BATCHSIZE))
  757. n = len(tmp)
  758. if n > 1:
  759. write(MARK)
  760. for k, v in tmp:
  761. save(k)
  762. save(v)
  763. write(SETITEMS)
  764. elif n:
  765. k, v = tmp[0]
  766. save(k)
  767. save(v)
  768. write(SETITEM)
  769. # else tmp is empty, and we're done
  770. if n < self._BATCHSIZE:
  771. return
  772. def save_set(self, obj):
  773. save = self.save
  774. write = self.write
  775. if self.proto < 4:
  776. self.save_reduce(set, (list(obj),), obj=obj)
  777. return
  778. write(EMPTY_SET)
  779. self.memoize(obj)
  780. it = iter(obj)
  781. while True:
  782. batch = list(islice(it, self._BATCHSIZE))
  783. n = len(batch)
  784. if n > 0:
  785. write(MARK)
  786. for item in batch:
  787. save(item)
  788. write(ADDITEMS)
  789. if n < self._BATCHSIZE:
  790. return
  791. dispatch[set] = save_set
  792. def save_frozenset(self, obj):
  793. save = self.save
  794. write = self.write
  795. if self.proto < 4:
  796. self.save_reduce(frozenset, (list(obj),), obj=obj)
  797. return
  798. write(MARK)
  799. for item in obj:
  800. save(item)
  801. if id(obj) in self.memo:
  802. # If the object is already in the memo, this means it is
  803. # recursive. In this case, throw away everything we put on the
  804. # stack, and fetch the object back from the memo.
  805. write(POP_MARK + self.get(self.memo[id(obj)][0]))
  806. return
  807. write(FROZENSET)
  808. self.memoize(obj)
  809. dispatch[frozenset] = save_frozenset
  810. def save_global(self, obj, name=None):
  811. write = self.write
  812. memo = self.memo
  813. if name is None:
  814. name = getattr(obj, '__qualname__', None)
  815. if name is None:
  816. name = obj.__name__
  817. module_name = whichmodule(obj, name)
  818. try:
  819. __import__(module_name, level=0)
  820. module = sys.modules[module_name]
  821. obj2, parent = _getattribute(module, name)
  822. except (ImportError, KeyError, AttributeError):
  823. raise PicklingError(
  824. "Can't pickle %r: it's not found as %s.%s" %
  825. (obj, module_name, name)) from None
  826. else:
  827. if obj2 is not obj:
  828. raise PicklingError(
  829. "Can't pickle %r: it's not the same object as %s.%s" %
  830. (obj, module_name, name))
  831. if self.proto >= 2:
  832. code = _extension_registry.get((module_name, name))
  833. if code:
  834. assert code > 0
  835. if code <= 0xff:
  836. write(EXT1 + pack("<B", code))
  837. elif code <= 0xffff:
  838. write(EXT2 + pack("<H", code))
  839. else:
  840. write(EXT4 + pack("<i", code))
  841. return
  842. lastname = name.rpartition('.')[2]
  843. if parent is module:
  844. name = lastname
  845. # Non-ASCII identifiers are supported only with protocols >= 3.
  846. if self.proto >= 4:
  847. self.save(module_name)
  848. self.save(name)
  849. write(STACK_GLOBAL)
  850. elif parent is not module:
  851. self.save_reduce(getattr, (parent, lastname))
  852. elif self.proto >= 3:
  853. write(GLOBAL + bytes(module_name, "utf-8") + b'\n' +
  854. bytes(name, "utf-8") + b'\n')
  855. else:
  856. if self.fix_imports:
  857. r_name_mapping = _compat_pickle.REVERSE_NAME_MAPPING
  858. r_import_mapping = _compat_pickle.REVERSE_IMPORT_MAPPING
  859. if (module_name, name) in r_name_mapping:
  860. module_name, name = r_name_mapping[(module_name, name)]
  861. elif module_name in r_import_mapping:
  862. module_name = r_import_mapping[module_name]
  863. try:
  864. write(GLOBAL + bytes(module_name, "ascii") + b'\n' +
  865. bytes(name, "ascii") + b'\n')
  866. except UnicodeEncodeError:
  867. raise PicklingError(
  868. "can't pickle global identifier '%s.%s' using "
  869. "pickle protocol %i" % (module, name, self.proto)) from None
  870. self.memoize(obj)
  871. def save_type(self, obj):
  872. if obj is type(None):
  873. return self.save_reduce(type, (None,), obj=obj)
  874. elif obj is type(NotImplemented):
  875. return self.save_reduce(type, (NotImplemented,), obj=obj)
  876. elif obj is type(...):
  877. return self.save_reduce(type, (...,), obj=obj)
  878. return self.save_global(obj)
  879. dispatch[FunctionType] = save_global
  880. dispatch[type] = save_type
  881. # Unpickling machinery
  882. class _Unpickler:
  883. def __init__(self, file, *, fix_imports=True,
  884. encoding="ASCII", errors="strict"):
  885. """This takes a binary file for reading a pickle data stream.
  886. The protocol version of the pickle is detected automatically, so
  887. no proto argument is needed.
  888. The argument *file* must have two methods, a read() method that
  889. takes an integer argument, and a readline() method that requires
  890. no arguments. Both methods should return bytes. Thus *file*
  891. can be a binary file object opened for reading, an io.BytesIO
  892. object, or any other custom object that meets this interface.
  893. The file-like object must have two methods, a read() method
  894. that takes an integer argument, and a readline() method that
  895. requires no arguments. Both methods should return bytes.
  896. Thus file-like object can be a binary file object opened for
  897. reading, a BytesIO object, or any other custom object that
  898. meets this interface.
  899. Optional keyword arguments are *fix_imports*, *encoding* and
  900. *errors*, which are used to control compatibility support for
  901. pickle stream generated by Python 2. If *fix_imports* is True,
  902. pickle will try to map the old Python 2 names to the new names
  903. used in Python 3. The *encoding* and *errors* tell pickle how
  904. to decode 8-bit string instances pickled by Python 2; these
  905. default to 'ASCII' and 'strict', respectively. *encoding* can be
  906. 'bytes' to read theses 8-bit string instances as bytes objects.
  907. """
  908. self._file_readline = file.readline
  909. self._file_read = file.read
  910. self.memo = {}
  911. self.encoding = encoding
  912. self.errors = errors
  913. self.proto = 0
  914. self.fix_imports = fix_imports
  915. def load(self):
  916. """Read a pickled object representation from the open file.
  917. Return the reconstituted object hierarchy specified in the file.
  918. """
  919. # Check whether Unpickler was initialized correctly. This is
  920. # only needed to mimic the behavior of _pickle.Unpickler.dump().
  921. if not hasattr(self, "_file_read"):
  922. raise UnpicklingError("Unpickler.__init__() was not called by "
  923. "%s.__init__()" % (self.__class__.__name__,))
  924. self._unframer = _Unframer(self._file_read, self._file_readline)
  925. self.read = self._unframer.read
  926. self.readline = self._unframer.readline
  927. self.metastack = []
  928. self.stack = []
  929. self.append = self.stack.append
  930. self.proto = 0
  931. read = self.read
  932. dispatch = self.dispatch
  933. try:
  934. while True:
  935. key = read(1)
  936. if not key:
  937. raise EOFError
  938. assert isinstance(key, bytes_types)
  939. dispatch[key[0]](self)
  940. except _Stop as stopinst:
  941. return stopinst.value
  942. # Return a list of items pushed in the stack after last MARK instruction.
  943. def pop_mark(self):
  944. items = self.stack
  945. self.stack = self.metastack.pop()
  946. self.append = self.stack.append
  947. return items
  948. def persistent_load(self, pid):
  949. raise UnpicklingError("unsupported persistent id encountered")
  950. dispatch = {}
  951. def load_proto(self):
  952. proto = self.read(1)[0]
  953. if not 0 <= proto <= HIGHEST_PROTOCOL:
  954. raise ValueError("unsupported pickle protocol: %d" % proto)
  955. self.proto = proto
  956. dispatch[PROTO[0]] = load_proto
  957. def load_frame(self):
  958. frame_size, = unpack('<Q', self.read(8))
  959. if frame_size > sys.maxsize:
  960. raise ValueError("frame size > sys.maxsize: %d" % frame_size)
  961. self._unframer.load_frame(frame_size)
  962. dispatch[FRAME[0]] = load_frame
  963. def load_persid(self):
  964. try:
  965. pid = self.readline()[:-1].decode("ascii")
  966. except UnicodeDecodeError:
  967. raise UnpicklingError(
  968. "persistent IDs in protocol 0 must be ASCII strings")
  969. self.append(self.persistent_load(pid))
  970. dispatch[PERSID[0]] = load_persid
  971. def load_binpersid(self):
  972. pid = self.stack.pop()
  973. self.append(self.persistent_load(pid))
  974. dispatch[BINPERSID[0]] = load_binpersid
  975. def load_none(self):
  976. self.append(None)
  977. dispatch[NONE[0]] = load_none
  978. def load_false(self):
  979. self.append(False)
  980. dispatch[NEWFALSE[0]] = load_false
  981. def load_true(self):
  982. self.append(True)
  983. dispatch[NEWTRUE[0]] = load_true
  984. def load_int(self):
  985. data = self.readline()
  986. if data == FALSE[1:]:
  987. val = False
  988. elif data == TRUE[1:]:
  989. val = True
  990. else:
  991. val = int(data, 0)
  992. self.append(val)
  993. dispatch[INT[0]] = load_int
  994. def load_binint(self):
  995. self.append(unpack('<i', self.read(4))[0])
  996. dispatch[BININT[0]] = load_binint
  997. def load_binint1(self):
  998. self.append(self.read(1)[0])
  999. dispatch[BININT1[0]] = load_binint1
  1000. def load_binint2(self):
  1001. self.append(unpack('<H', self.read(2))[0])
  1002. dispatch[BININT2[0]] = load_binint2
  1003. def load_long(self):
  1004. val = self.readline()[:-1]
  1005. if val and val[-1] == b'L'[0]:
  1006. val = val[:-1]
  1007. self.append(int(val, 0))
  1008. dispatch[LONG[0]] = load_long
  1009. def load_long1(self):
  1010. n = self.read(1)[0]
  1011. data = self.read(n)
  1012. self.append(decode_long(data))
  1013. dispatch[LONG1[0]] = load_long1
  1014. def load_long4(self):
  1015. n, = unpack('<i', self.read(4))
  1016. if n < 0:
  1017. # Corrupt or hostile pickle -- we never write one like this
  1018. raise UnpicklingError("LONG pickle has negative byte count")
  1019. data = self.read(n)
  1020. self.append(decode_long(data))
  1021. dispatch[LONG4[0]] = load_long4
  1022. def load_float(self):
  1023. self.append(float(self.readline()[:-1]))
  1024. dispatch[FLOAT[0]] = load_float
  1025. def load_binfloat(self):
  1026. self.append(unpack('>d', self.read(8))[0])
  1027. dispatch[BINFLOAT[0]] = load_binfloat
  1028. def _decode_string(self, value):
  1029. # Used to allow strings from Python 2 to be decoded either as
  1030. # bytes or Unicode strings. This should be used only with the
  1031. # STRING, BINSTRING and SHORT_BINSTRING opcodes.
  1032. if self.encoding == "bytes":
  1033. return value
  1034. else:
  1035. return value.decode(self.encoding, self.errors)
  1036. def load_string(self):
  1037. data = self.readline()[:-1]
  1038. # Strip outermost quotes
  1039. if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'':
  1040. data = data[1:-1]
  1041. else:
  1042. raise UnpicklingError("the STRING opcode argument must be quoted")
  1043. self.append(self._decode_string(codecs.escape_decode(data)[0]))
  1044. dispatch[STRING[0]] = load_string
  1045. def load_binstring(self):
  1046. # Deprecated BINSTRING uses signed 32-bit length
  1047. len, = unpack('<i', self.read(4))
  1048. if len < 0:
  1049. raise UnpicklingError("BINSTRING pickle has negative byte count")
  1050. data = self.read(len)
  1051. self.append(self._decode_string(data))
  1052. dispatch[BINSTRING[0]] = load_binstring
  1053. def load_binbytes(self):
  1054. len, = unpack('<I', self.read(4))
  1055. if len > maxsize:
  1056. raise UnpicklingError("BINBYTES exceeds system's maximum size "
  1057. "of %d bytes" % maxsize)
  1058. self.append(self.read(len))
  1059. dispatch[BINBYTES[0]] = load_binbytes
  1060. def load_unicode(self):
  1061. self.append(str(self.readline()[:-1], 'raw-unicode-escape'))
  1062. dispatch[UNICODE[0]] = load_unicode
  1063. def load_binunicode(self):
  1064. len, = unpack('<I', self.read(4))
  1065. if len > maxsize:
  1066. raise UnpicklingError("BINUNICODE exceeds system's maximum size "
  1067. "of %d bytes" % maxsize)
  1068. self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
  1069. dispatch[BINUNICODE[0]] = load_binunicode
  1070. def load_binunicode8(self):
  1071. len, = unpack('<Q', self.read(8))
  1072. if len > maxsize:
  1073. raise UnpicklingError("BINUNICODE8 exceeds system's maximum size "
  1074. "of %d bytes" % maxsize)
  1075. self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
  1076. dispatch[BINUNICODE8[0]] = load_binunicode8
  1077. def load_binbytes8(self):
  1078. len, = unpack('<Q', self.read(8))
  1079. if len > maxsize:
  1080. raise UnpicklingError("BINBYTES8 exceeds system's maximum size "
  1081. "of %d bytes" % maxsize)
  1082. self.append(self.read(len))
  1083. dispatch[BINBYTES8[0]] = load_binbytes8
  1084. def load_short_binstring(self):
  1085. len = self.read(1)[0]
  1086. data = self.read(len)
  1087. self.append(self._decode_string(data))
  1088. dispatch[SHORT_BINSTRING[0]] = load_short_binstring
  1089. def load_short_binbytes(self):
  1090. len = self.read(1)[0]
  1091. self.append(self.read(len))
  1092. dispatch[SHORT_BINBYTES[0]] = load_short_binbytes
  1093. def load_short_binunicode(self):
  1094. len = self.read(1)[0]
  1095. self.append(str(self.read(len), 'utf-8', 'surrogatepass'))
  1096. dispatch[SHORT_BINUNICODE[0]] = load_short_binunicode
  1097. def load_tuple(self):
  1098. items = self.pop_mark()
  1099. self.append(tuple(items))
  1100. dispatch[TUPLE[0]] = load_tuple
  1101. def load_empty_tuple(self):
  1102. self.append(())
  1103. dispatch[EMPTY_TUPLE[0]] = load_empty_tuple
  1104. def load_tuple1(self):
  1105. self.stack[-1] = (self.stack[-1],)
  1106. dispatch[TUPLE1[0]] = load_tuple1
  1107. def load_tuple2(self):
  1108. self.stack[-2:] = [(self.stack[-2], self.stack[-1])]
  1109. dispatch[TUPLE2[0]] = load_tuple2
  1110. def load_tuple3(self):
  1111. self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])]
  1112. dispatch[TUPLE3[0]] = load_tuple3
  1113. def load_empty_list(self):
  1114. self.append([])
  1115. dispatch[EMPTY_LIST[0]] = load_empty_list
  1116. def load_empty_dictionary(self):
  1117. self.append({})
  1118. dispatch[EMPTY_DICT[0]] = load_empty_dictionary
  1119. def load_empty_set(self):
  1120. self.append(set())
  1121. dispatch[EMPTY_SET[0]] = load_empty_set
  1122. def load_frozenset(self):
  1123. items = self.pop_mark()
  1124. self.append(frozenset(items))
  1125. dispatch[FROZENSET[0]] = load_frozenset
  1126. def load_list(self):
  1127. items = self.pop_mark()
  1128. self.append(items)
  1129. dispatch[LIST[0]] = load_list
  1130. def load_dict(self):
  1131. items = self.pop_mark()
  1132. d = {items[i]: items[i+1]
  1133. for i in range(0, len(items), 2)}
  1134. self.append(d)
  1135. dispatch[DICT[0]] = load_dict
  1136. # INST and OBJ differ only in how they get a class object. It's not
  1137. # only sensible to do the rest in a common routine, the two routines
  1138. # previously diverged and grew different bugs.
  1139. # klass is the class to instantiate, and k points to the topmost mark
  1140. # object, following which are the arguments for klass.__init__.
  1141. def _instantiate(self, klass, args):
  1142. if (args or not isinstance(klass, type) or
  1143. hasattr(klass, "__getinitargs__")):
  1144. try:
  1145. value = klass(*args)
  1146. except TypeError as err:
  1147. raise TypeError("in constructor for %s: %s" %
  1148. (klass.__name__, str(err)), sys.exc_info()[2])
  1149. else:
  1150. value = klass.__new__(klass)
  1151. self.append(value)
  1152. def load_inst(self):
  1153. module = self.readline()[:-1].decode("ascii")
  1154. name = self.readline()[:-1].decode("ascii")
  1155. klass = self.find_class(module, name)
  1156. self._instantiate(klass, self.pop_mark())
  1157. dispatch[INST[0]] = load_inst
  1158. def load_obj(self):
  1159. # Stack is ... markobject classobject arg1 arg2 ...
  1160. args = self.pop_mark()
  1161. cls = args.pop(0)
  1162. self._instantiate(cls, args)
  1163. dispatch[OBJ[0]] = load_obj
  1164. def load_newobj(self):
  1165. args = self.stack.pop()
  1166. cls = self.stack.pop()
  1167. obj = cls.__new__(cls, *args)
  1168. self.append(obj)
  1169. dispatch[NEWOBJ[0]] = load_newobj
  1170. def load_newobj_ex(self):
  1171. kwargs = self.stack.pop()
  1172. args = self.stack.pop()
  1173. cls = self.stack.pop()
  1174. obj = cls.__new__(cls, *args, **kwargs)
  1175. self.append(obj)
  1176. dispatch[NEWOBJ_EX[0]] = load_newobj_ex
  1177. def load_global(self):
  1178. module = self.readline()[:-1].decode("utf-8")
  1179. name = self.readline()[:-1].decode("utf-8")
  1180. klass = self.find_class(module, name)
  1181. self.append(klass)
  1182. dispatch[GLOBAL[0]] = load_global
  1183. def load_stack_global(self):
  1184. name = self.stack.pop()
  1185. module = self.stack.pop()
  1186. if type(name) is not str or type(module) is not str:
  1187. raise UnpicklingError("STACK_GLOBAL requires str")
  1188. self.append(self.find_class(module, name))
  1189. dispatch[STACK_GLOBAL[0]] = load_stack_global
  1190. def load_ext1(self):
  1191. code = self.read(1)[0]
  1192. self.get_extension(code)
  1193. dispatch[EXT1[0]] = load_ext1
  1194. def load_ext2(self):
  1195. code, = unpack('<H', self.read(2))
  1196. self.get_extension(code)
  1197. dispatch[EXT2[0]] = load_ext2
  1198. def load_ext4(self):
  1199. code, = unpack('<i', self.read(4))
  1200. self.get_extension(code)
  1201. dispatch[EXT4[0]] = load_ext4
  1202. def get_extension(self, code):
  1203. nil = []
  1204. obj = _extension_cache.get(code, nil)
  1205. if obj is not nil:
  1206. self.append(obj)
  1207. return
  1208. key = _inverted_registry.get(code)
  1209. if not key:
  1210. if code <= 0: # note that 0 is forbidden
  1211. # Corrupt or hostile pickle.
  1212. raise UnpicklingError("EXT specifies code <= 0")
  1213. raise ValueError("unregistered extension code %d" % code)
  1214. obj = self.find_class(*key)
  1215. _extension_cache[code] = obj
  1216. self.append(obj)
  1217. def find_class(self, module, name):
  1218. # Subclasses may override this.
  1219. if self.proto < 3 and self.fix_imports:
  1220. if (module, name) in _compat_pickle.NAME_MAPPING:
  1221. module, name = _compat_pickle.NAME_MAPPING[(module, name)]
  1222. elif module in _compat_pickle.IMPORT_MAPPING:
  1223. module = _compat_pickle.IMPORT_MAPPING[module]
  1224. __import__(module, level=0)
  1225. if self.proto >= 4:
  1226. return _getattribute(sys.modules[module], name)[0]
  1227. else:
  1228. return getattr(sys.modules[module], name)
  1229. def load_reduce(self):
  1230. stack = self.stack
  1231. args = stack.pop()
  1232. func = stack[-1]
  1233. stack[-1] = func(*args)
  1234. dispatch[REDUCE[0]] = load_reduce
  1235. def load_pop(self):
  1236. if self.stack:
  1237. del self.stack[-1]
  1238. else:
  1239. self.pop_mark()
  1240. dispatch[POP[0]] = load_pop
  1241. def load_pop_mark(self):
  1242. self.pop_mark()
  1243. dispatch[POP_MARK[0]] = load_pop_mark
  1244. def load_dup(self):
  1245. self.append(self.stack[-1])
  1246. dispatch[DUP[0]] = load_dup
  1247. def load_get(self):
  1248. i = int(self.readline()[:-1])
  1249. self.append(self.memo[i])
  1250. dispatch[GET[0]] = load_get
  1251. def load_binget(self):
  1252. i = self.read(1)[0]
  1253. self.append(self.memo[i])
  1254. dispatch[BINGET[0]] = load_binget
  1255. def load_long_binget(self):
  1256. i, = unpack('<I', self.read(4))
  1257. self.append(self.memo[i])
  1258. dispatch[LONG_BINGET[0]] = load_long_binget
  1259. def load_put(self):
  1260. i = int(self.readline()[:-1])
  1261. if i < 0:
  1262. raise ValueError("negative PUT argument")
  1263. self.memo[i] = self.stack[-1]
  1264. dispatch[PUT[0]] = load_put
  1265. def load_binput(self):
  1266. i = self.read(1)[0]
  1267. if i < 0:
  1268. raise ValueError("negative BINPUT argument")
  1269. self.memo[i] = self.stack[-1]
  1270. dispatch[BINPUT[0]] = load_binput
  1271. def load_long_binput(self):
  1272. i, = unpack('<I', self.read(4))
  1273. if i > maxsize:
  1274. raise ValueError("negative LONG_BINPUT argument")
  1275. self.memo[i] = self.stack[-1]
  1276. dispatch[LONG_BINPUT[0]] = load_long_binput
  1277. def load_memoize(self):
  1278. memo = self.memo
  1279. memo[len(memo)] = self.stack[-1]
  1280. dispatch[MEMOIZE[0]] = load_memoize
  1281. def load_append(self):
  1282. stack = self.stack
  1283. value = stack.pop()
  1284. list = stack[-1]
  1285. list.append(value)
  1286. dispatch[APPEND[0]] = load_append
  1287. def load_appends(self):
  1288. items = self.pop_mark()
  1289. list_obj = self.stack[-1]
  1290. try:
  1291. extend = list_obj.extend
  1292. except AttributeError:
  1293. pass
  1294. else:
  1295. extend(items)
  1296. return
  1297. # Even if the PEP 307 requires extend() and append() methods,
  1298. # fall back on append() if the object has no extend() method
  1299. # for backward compatibility.
  1300. append = list_obj.append
  1301. for item in items:
  1302. append(item)
  1303. dispatch[APPENDS[0]] = load_appends
  1304. def load_setitem(self):
  1305. stack = self.stack
  1306. value = stack.pop()
  1307. key = stack.pop()
  1308. dict = stack[-1]
  1309. dict[key] = value
  1310. dispatch[SETITEM[0]] = load_setitem
  1311. def load_setitems(self):
  1312. items = self.pop_mark()
  1313. dict = self.stack[-1]
  1314. for i in range(0, len(items), 2):
  1315. dict[items[i]] = items[i + 1]
  1316. dispatch[SETITEMS[0]] = load_setitems
  1317. def load_additems(self):
  1318. items = self.pop_mark()
  1319. set_obj = self.stack[-1]
  1320. if isinstance(set_obj, set):
  1321. set_obj.update(items)
  1322. else:
  1323. add = set_obj.add
  1324. for item in items:
  1325. add(item)
  1326. dispatch[ADDITEMS[0]] = load_additems
  1327. def load_build(self):
  1328. stack = self.stack
  1329. state = stack.pop()
  1330. inst = stack[-1]
  1331. setstate = getattr(inst, "__setstate__", None)
  1332. if setstate is not None:
  1333. setstate(state)
  1334. return
  1335. slotstate = None
  1336. if isinstance(state, tuple) and len(state) == 2:
  1337. state, slotstate = state
  1338. if state:
  1339. inst_dict = inst.__dict__
  1340. intern = sys.intern
  1341. for k, v in state.items():
  1342. if type(k) is str:
  1343. inst_dict[intern(k)] = v
  1344. else:
  1345. inst_dict[k] = v
  1346. if slotstate:
  1347. for k, v in slotstate.items():
  1348. setattr(inst, k, v)
  1349. dispatch[BUILD[0]] = load_build
  1350. def load_mark(self):
  1351. self.metastack.append(self.stack)
  1352. self.stack = []
  1353. self.append = self.stack.append
  1354. dispatch[MARK[0]] = load_mark
  1355. def load_stop(self):
  1356. value = self.stack.pop()
  1357. raise _Stop(value)
  1358. dispatch[STOP[0]] = load_stop
  1359. # Shorthands
  1360. def _dump(obj, file, protocol=None, *, fix_imports=True):
  1361. _Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
  1362. def _dumps(obj, protocol=None, *, fix_imports=True):
  1363. f = io.BytesIO()
  1364. _Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
  1365. res = f.getvalue()
  1366. assert isinstance(res, bytes_types)
  1367. return res
  1368. def _load(file, *, fix_imports=True, encoding="ASCII", errors="strict"):
  1369. return _Unpickler(file, fix_imports=fix_imports,
  1370. encoding=encoding, errors=errors).load()
  1371. def _loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"):
  1372. if isinstance(s, str):
  1373. raise TypeError("Can't load pickle from unicode string")
  1374. file = io.BytesIO(s)
  1375. return _Unpickler(file, fix_imports=fix_imports,
  1376. encoding=encoding, errors=errors).load()
  1377. # Use the faster _pickle if possible
  1378. try:
  1379. from _pickle import (
  1380. PickleError,
  1381. PicklingError,
  1382. UnpicklingError,
  1383. Pickler,
  1384. Unpickler,
  1385. dump,
  1386. dumps,
  1387. load,
  1388. loads
  1389. )
  1390. except ImportError:
  1391. Pickler, Unpickler = _Pickler, _Unpickler
  1392. dump, dumps, load, loads = _dump, _dumps, _load, _loads
  1393. # Doctest
  1394. def _test():
  1395. import doctest
  1396. return doctest.testmod()
  1397. if __name__ == "__main__":
  1398. import argparse
  1399. parser = argparse.ArgumentParser(
  1400. description='display contents of the pickle files')
  1401. parser.add_argument(
  1402. 'pickle_file', type=argparse.FileType('br'),
  1403. nargs='*', help='the pickle file')
  1404. parser.add_argument(
  1405. '-t', '--test', action='store_true',
  1406. help='run self-test suite')
  1407. parser.add_argument(
  1408. '-v', action='store_true',
  1409. help='run verbosely; only affects self-test run')
  1410. args = parser.parse_args()
  1411. if args.test:
  1412. _test()
  1413. else:
  1414. if not args.pickle_file:
  1415. parser.print_help()
  1416. else:
  1417. import pprint
  1418. for f in args.pickle_file:
  1419. obj = load(f)
  1420. pprint.pprint(obj)