pickle.py 65 KB

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