pickle.py 65 KB

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