pickle.py 55 KB

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