f=cE@sdZddlZddlZddlZddlZdddgZejZd Zd Zd Z d Z Gd d d e Z dd l mZd dZe dddddeddZddZe dddddeddZddZe dddd deddZddZe dddd dedd Zeed!d"Ze dd#dededd$Zd%d&Ze dd'dededd(Zd)d*Ze dd+dededd,Zd-d.Ze dd/de dedd0Z d1d2Z!e dd3dede!dd4Z"d5d6Z#e dd7dede#dd8Z$d9d:Z%e dd;de de%dd<Z&d=d>Z'e dd?dede'dd@Z(dAdBZ)e ddCde de)ddDZ*dEdFZ+dGdHZ,e ddIdede+ddJZ-e ddKdede,ddLZ.dMdNZ/e ddOdede/ddPZ0dQdRZ1e ddSddTde1ddUZ2ddVlm3Z3dWdXZ4e ddYdede4ddZZ5d[d\Z6e dd]de de6dd^Z7Gd_d`d`e Z8e8ddadbe9ddcZ:e8ddddbe9ddeZ;e8ddfdbe9e<fddgZ=e8ddhdbe<fddiZ>e8ddjdbe?ddkZ@e8ddldbeAddmZBe8ddndbeAddoZCe8ddpdbeDddqZEe8ddrdbeFeGddsZHe8ddtdbeIdduZJe8ddvdbeKddwZLe8ddxdbeMddyZNe8ddzdbe dd{ZOe8dd|dbe8dd}ZPe8dd~dbe8ddZQGddde ZReRZSeSddddde-dgde=gddddeSdddddedgde:gddddeSdddddedgde:gddddeSdddddedgde:gddddeSddddde.dgde;gddddeSddddde5dgde;gddddeSddddde7dgde;gddddeSdddddedgdeBgddddeSddddde dgdeBgddddeSddddde"dgdeBgddddeSddddde&dgdeCgddddeSddddde$dgdeCgddddeSdddddeGdgdeHgddddeSdddddeGdgde>gddddeSdddddeGdgde>gddddeSddddde(dgdeEgddddeSddddde*dgdeEgddddeSddddde0dgde@gddddeSddddde2dgde@gddddeSdddddeGdgdeLgddddeSdddddeGdeLeOgdeLgddddeSdddddeGdeLePeQgdeLgddddeSdddddeGdePeQgdeLgddddeSdddddeGdgdeJgddddeSdddddeGdePeQgdeJgddddeSdddddeGdeOgdeJgddddeSdddddeGdeOeOgdeJgddddeSdddddeGdeOeOeOgdeJgddddeSdddddeGdgdeNgddddeSdddddeGdePeQgdeNgddddeSdddddeGdeNeOeOgdeNgddddeSdddddeGdeNePeQgdeNgddddeSdddddeGdeOgdgddddeSdddddeGdeOgdeOeOgddddeSdddddeGdgdePgddddeSdddddeGdePeQgdgddddeSddddde-dgdeOgddddeSdddddedgdeOgddddeSdddddedgdeOgddddeSddddde-dgdgddddeSdddddedgdgddddeSdddddedgdgddddeSdddddedgdeOgddddeSdddd dedgdeOgdddd eSdd dd dedgdeOgdddd eSdddddedgdeOgddddeSdddddeGdeOeOgdeOgddddeSdddddeGdeOeOgdeOgddddeSdddddedePeQgdeOgddddeSdddddeGdePeOeQgdeOgddddeSdddddeGdeOeOgdeOgddddeSdd dd!dedgdgdddd"eSdd#dd$deGdeOgdgdddd%eSdd&dd'dedgdeOgdddd(eSdd)dd*deGdeOgdeOgdddd+g7ZT[SiZUiZVxeWeTD]\ZXZYeYjZeUkre[d,eYjZeUeYjZeXfneYj\eVkre[d-eYj\eVeYj\eXfneXeUeYjZd?eijmd@dAdBdCdDekjldEdFdGejnd?eijmdHdCdIekjldJdKdLdMdCdNekjldOdPdGd d?e9dCdQekjldRdSdLdMdCdTekjldUdVdGdWdCdXekjldYdZdLdMdCd[ekjld\dLdMdCd]ekjoZpepjqregnepjrrd^ndZrepjs r!ekjtneuepjsdkr\ebepjsdepjveGepjwernqepjxrkineGZxxYepjsD]NZyepjzj{deyjZZzepjvj|ezd_ebeyepjvexepjwerq{WndS(`ur"Executable documentation" for the pickle module. Extensive comments about the pickle protocols and pickle-machine opcodes can be found here. Some functions meant for external use: genops(pickle) Generate all the opcodes in a pickle, as (opcode, arg, position) triples. dis(pickle, out=None, memo=None, indentlevel=4) Print a symbolic disassembly of a pickle. iNudisugenopsuoptimizeiiiicBs&|EeZdZdZddZdS( uArgumentDescriptorunameunureaderudoccCst|tst||_t|trQ|dksW|ttttfksWt||_ ||_ t|ts~t||_ dS(Ni( u isinstanceustruAssertionErrorunameuintu UP_TO_NEWLINEuTAKEN_FROM_ARGUMENT1uTAKEN_FROM_ARGUMENT4uTAKEN_FROM_ARGUMENT4Uunureaderudoc(uselfunameunureaderudoc((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu__init__s   uArgumentDescriptor.__init__N(unameunureaderudoc(u__name__u __module__u __qualname__u __slots__u__init__(u __locals__((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuArgumentDescriptors uArgumentDescriptor(uunpackcCs-|jd}|r|dStddS(uG >>> import io >>> read_uint1(io.BytesIO(b'\xff')) 255 iiu'not enough data in stream to read uint1N(ureadu ValueError(ufudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_uint1su read_uint1unameuuint1unureaderudocuOne-byte unsigned integer.cCsB|jd}t|dkr2td|dStddS(u >>> import io >>> read_uint2(io.BytesIO(b'\xff\x00')) 255 >>> read_uint2(io.BytesIO(b'\xff\xff')) 65535 iu>> import io >>> read_int4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_int4(io.BytesIO(b'\x00\x00\x00\x80')) == -(2**31) True iu>> import io >>> read_uint4(io.BytesIO(b'\xff\x00\x00\x00')) 255 >>> read_uint4(io.BytesIO(b'\x00\x00\x00\x80')) == 2**31 True iu>> import io >>> read_stringnl(io.BytesIO(b"'abcd'\nefg\n")) 'abcd' >>> read_stringnl(io.BytesIO(b"\n")) Traceback (most recent call last): ... ValueError: no string quotes around b'' >>> read_stringnl(io.BytesIO(b"\n"), stripquotes=False) '' >>> read_stringnl(io.BytesIO(b"''\n")) '' >>> read_stringnl(io.BytesIO(b'"abcd"')) Traceback (most recent call last): ... ValueError: no newline found when trying to read stringnl Embedded escapes are undone in the result. >>> read_stringnl(io.BytesIO(br"'a\n\\b\x00c\td'" + b"\n'e'")) 'a\n\\b\x00c\td' s u-no newline found when trying to read stringnlNis"s'u,strinq quote %r not found at both ends of %runo string quotes around %riuasciii(s"s'i(ureadlineuendswithu ValueErroru startswithucodecsu escape_decodeudecode(ufudecodeu stripquotesudatauq((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_stringnl$s   u read_stringnlustringnluA newline-terminated string. This is a repr-style string, with embedded escapes, and bracketing quotes. cCst|ddS(Nu stripquotesF(u read_stringnluFalse(uf((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuread_stringnl_noescape]suread_stringnl_noescapeustringnl_noescapeuA newline-terminated string. This is a str-style string, without embedded escapes, or bracketing quotes. It should consist solely of printable ASCII characters. cCsdt|t|fS(up >>> import io >>> read_stringnl_noescape_pair(io.BytesIO(b"Queue\nEmpty\njunk")) 'Queue Empty' u%s %s(uread_stringnl_noescape(uf((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuread_stringnl_noescape_pairksuread_stringnl_noescape_pairustringnl_noescape_pairuA pair of newline-terminated strings. These are str-style strings, without embedded escapes, or bracketing quotes. They should consist solely of printable ASCII characters. The pair is returned as a single string, with a single blank separating the two strings. cCsyt|}|dkr+td|n|j|}t||krY|jdStd|t|fdS(uP >>> import io >>> read_string4(io.BytesIO(b"\x00\x00\x00\x00abc")) '' >>> read_string4(io.BytesIO(b"\x03\x00\x00\x00abcdef")) 'abc' >>> read_string4(io.BytesIO(b"\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a string4, but only 6 remain iustring4 byte count < 0: %dulatin-1u2expected %d bytes in a string4, but only %d remainN(u read_int4u ValueErrorureadulenudecode(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_string4s   u read_string4ustring4uA counted string. The first argument is a 4-byte little-endian signed int giving the number of bytes in the string, and the second argument is that many bytes. cCslt|}|dkst|j|}t||krL|jdStd|t|fdS(u >>> import io >>> read_string1(io.BytesIO(b"\x00")) '' >>> read_string1(io.BytesIO(b"\x03abcdef")) 'abc' iulatin-1u2expected %d bytes in a string1, but only %d remainN(u read_uint1uAssertionErrorureadulenudecodeu ValueError(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_string1s  u read_string1ustring1uA counted string. The first argument is a 1-byte unsigned int giving the number of bytes in the string, and the second argument is that many bytes. cCsct|}|dkst|j|}t||krC|Std|t|fdS(u >>> import io >>> read_bytes1(io.BytesIO(b"\x00")) b'' >>> read_bytes1(io.BytesIO(b"\x03abcdef")) b'abc' iu1expected %d bytes in a bytes1, but only %d remainN(u read_uint1uAssertionErrorureadulenu ValueError(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_bytes1s u read_bytes1ubytes1uA counted bytes string. The first argument is a 1-byte unsigned int giving the number of bytes, and the second argument is that many bytes. cCsst|}|tjkr.td|n|j|}t||krS|Std|t|fdS(uN >>> import io >>> read_bytes4(io.BytesIO(b"\x00\x00\x00\x00abc")) b'' >>> read_bytes4(io.BytesIO(b"\x03\x00\x00\x00abcdef")) b'abc' >>> read_bytes4(io.BytesIO(b"\x00\x00\x00\x03abcdef")) Traceback (most recent call last): ... ValueError: expected 50331648 bytes in a bytes4, but only 6 remain u#bytes4 byte count > sys.maxsize: %du1expected %d bytes in a bytes4, but only %d remainN(u read_uint4usysumaxsizeu ValueErrorureadulen(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_bytes4s u read_bytes4ubytes4uA counted bytes string. The first argument is a 4-byte little-endian unsigned int giving the number of bytes, and the second argument is that many bytes. cCsG|j}|jds*tdn|dd}t|dS(um >>> import io >>> read_unicodestringnl(io.BytesIO(b"abc\\uabcd\njunk")) == 'abc\uabcd' True s u4no newline found when trying to read unicodestringnlNiuraw-unicode-escapei(ureadlineuendswithu ValueErrorustr(ufudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuread_unicodestringnls  uread_unicodestringnluunicodestringnluA newline-terminated Unicode string. This is raw-unicode-escape encoded, so consists of printable ASCII characters, and may contain embedded escape sequences. cCst|}|tjkr.td|n|j|}t||kr_t|ddStd|t|fdS(u >>> import io >>> s = 'abcd\uabcd' >>> enc = s.encode('utf-8') >>> enc b'abcd\xea\xaf\x8d' >>> n = bytes([len(enc), 0, 0, 0]) # little-endian 4-byte length >>> t = read_unicodestring4(io.BytesIO(n + enc + b'junk')) >>> s == t True >>> read_unicodestring4(io.BytesIO(n + enc[:-1])) Traceback (most recent call last): ... ValueError: expected 7 bytes in a unicodestring4, but only 6 remain u+unicodestring4 byte count > sys.maxsize: %duutf-8u surrogatepassu9expected %d bytes in a unicodestring4, but only %d remainN(u read_uint4usysumaxsizeu ValueErrorureadulenustr(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuread_unicodestring4s uread_unicodestring4uunicodestring4uAA counted Unicode string. The first argument is a 4-byte little-endian signed int giving the number of bytes in the string, and the second argument-- the UTF-8 encoding of the Unicode string -- contains that many bytes. cCsBt|dddd}|dkr(dS|dkr8dSt|S(u >>> import io >>> read_decimalnl_short(io.BytesIO(b"1234\n56")) 1234 >>> read_decimalnl_short(io.BytesIO(b"1234L\n56")) Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: b'1234L' udecodeu stripquotess00s01FT(u read_stringnluFalseuTrueuint(ufus((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuread_decimalnl_short>s   uread_decimalnl_shortcCsKt|dddd}|dddkrA|dd}nt|S( u >>> import io >>> read_decimalnl_long(io.BytesIO(b"1234L\n56")) 1234 >>> read_decimalnl_long(io.BytesIO(b"123456789012345678901234L\n6")) 123456789012345678901234 udecodeu stripquotesiNsLFii(u read_stringnluFalseuint(ufus((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuread_decimalnl_longTs uread_decimalnl_longudecimalnl_shortuA newline-terminated decimal integer literal. This never has a trailing 'L', and the integer fit in a short Python int on the box where the pickle was written -- but there's no guarantee it will fit in a short Python int on the box where the pickle is read. udecimalnl_longuA newline-terminated decimal integer literal. This has a trailing 'L', and can represent integers of any size. cCs"t|dddd}t|S(uO >>> import io >>> read_floatnl(io.BytesIO(b"-1.25\n6")) -1.25 udecodeu stripquotesF(u read_stringnluFalseufloat(ufus((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_floatnl}su read_floatnlufloatnluA newline-terminated decimal floating literal. In general this requires 17 significant digits for roundtrip identity, and pickling then unpickling infinities, NaNs, and minus zero doesn't work across boxes, or on some boxes even on itself (e.g., Windows can't read the strings it produces for infinities or NaNs). cCsB|jd}t|dkr2td|dStddS(u >>> import io, struct >>> raw = struct.pack(">d", -1.25) >>> raw b'\xbf\xf4\x00\x00\x00\x00\x00\x00' >>> read_float8(io.BytesIO(raw + b"\n")) -1.25 iu>diu(not enough data in stream to read float8N(ureadulenu_unpacku ValueError(ufudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_float8s u read_float8ufloat8iuAn 8-byte binary representation of a float, big-endian. The format is unique to Python, and shared with the struct module (format string '>d') "in theory" (the struct and pickle implementations don't share the code -- they should). It's strongly related to the IEEE-754 double format, and, in normal cases, is in fact identical to the big-endian 754 double format. On other boxes the dynamic range is limited to that of a 754 double, and "add a half and chop" rounding is used to reduce the precision to 53 bits. However, even on a 754 box, infinities, NaNs, and minus zero may not be handled correctly (may not survive roundtrip pickling intact). (u decode_longcCsFt|}|j|}t||kr<tdnt|S(u+ >>> import io >>> read_long1(io.BytesIO(b"\x00")) 0 >>> read_long1(io.BytesIO(b"\x02\xff\x00")) 255 >>> read_long1(io.BytesIO(b"\x02\xff\x7f")) 32767 >>> read_long1(io.BytesIO(b"\x02\x00\xff")) -256 >>> read_long1(io.BytesIO(b"\x02\x00\x80")) -32768 u'not enough data in stream to read long1(u read_uint1ureadulenu ValueErroru decode_long(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_long1s  u read_long1ulong1uA binary long, little-endian, using 1-byte size. This first reads one byte as an unsigned size, then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken as a shortcut for the long 0L. cCset|}|dkr+td|n|j|}t||kr[tdnt|S(ug >>> import io >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x00")) 255 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\xff\x7f")) 32767 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\xff")) -256 >>> read_long4(io.BytesIO(b"\x02\x00\x00\x00\x00\x80")) -32768 >>> read_long1(io.BytesIO(b"\x00\x00\x00\x00")) 0 iulong4 byte count < 0: %du'not enough data in stream to read long4(u read_int4u ValueErrorureadulenu decode_long(ufunudata((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu read_long4s  u read_long4ulong4uA binary representation of a long, little-endian. This first reads four bytes as a signed size (but requires the size to be >= 0), then reads that many bytes and interprets them as a little-endian 2's-complement long. If the size is 0, that's taken as a shortcut for the int 0, although LONG1 should really be used then instead (and in any case where # of bytes < 256). cBs2|EeZdZd ZddZddZdS( u StackObjectunameuobtypeudoccCst|tst||_t|tsBt|tsBtt|trzx&|D]}t|tsXtqXWn||_t|tst||_dS(N(u isinstanceustruAssertionErrorunameutypeutupleuobtypeudoc(uselfunameuobtypeudocu contained((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu__init__s $  uStackObject.__init__cCs|jS(N(uname(uself((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu__repr__suStackObject.__repr__N(unameuobtypeudoc(u__name__u __module__u __qualname__u __slots__u__init__u__repr__(u __locals__((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu StackObjects  u StackObjectuintuobtypeu3A short (as opposed to long) Python integer object.ulongu3A long (as opposed to short) Python integer object.u int_or_boolu:A Python integer object (short or long), or a Python bool.ubooluA Python bool object.ufloatuA Python float object.ustringuA Python (8-bit) string object.ubytesuA Python bytes object.ustru!A Python (Unicode) string object.uNoneuThe Python None object.utupleuA Python tuple object.ulistuA Python list object.udictuA Python dict object.uanyuAny kind of object whatsoever.umarku'The mark' is a unique object. Opcodes that operate on a variable number of objects generally don't embed the count of objects in the opcode, or pull it off the stack. Instead the MARK opcode is used to push a special marker object on the stack, and then some other opcodes grab all the objects from the top of the stack down to (but not including) the topmost marker object. u stacksliceuLAn object representing a contiguous slice of the stack. This is used in conjunction with markobject, to represent all of the stack following the topmost markobject. For example, the POP_MARK opcode changes the stack from [..., markobject, stackslice] to [...] No matter how many object are on the stack after the topmost markobject, POP_MARK gets rid of all of them (including the topmost markobject too). cBs&|EeZdZd Zdd Zd S( u OpcodeInfounameucodeuargu stack_beforeu stack_afteruprotoudocc Cset|tst||_t|ts3tt|dksKt||_|dksut|tsut||_t|t stx#|D]}t|t stqW||_ t|t stx#|D]}t|t stqW||_ t|t r4d|ko/tjkns:t||_t|tsXt||_dS(Nii(u isinstanceustruAssertionErrorunameulenucodeuNoneuArgumentDescriptoruargulistu StackObjectu stack_beforeu stack_afteruintupickleuHIGHEST_PROTOCOLuprotoudoc( uselfunameucodeuargu stack_beforeu stack_afteruprotoudocux((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu__init__s&  !     4 uOpcodeInfo.__init__N(unameucodeuargu stack_beforeu stack_afteruprotoudoc(u__name__u __module__u __qualname__u __slots__u__init__(u __locals__((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu OpcodeInfosu OpcodeInfouINTucodeuIuargu stack_beforeu stack_afteruprotouPush an integer or bool. The argument is a newline-terminated decimal literal string. The intent may have been that this always fit in a short Python int, but INT can be generated in pickles written on a 64-bit box that require a Python long on a 32-bit box. The difference between this and LONG then is that INT skips a trailing 'L', and produces a short int whenever possible. Another difference is due to that, when bool was introduced as a distinct type in 2.3, builtin names True and False were also added to 2.2.2, mapping to ints 1 and 0. For compatibility in both directions, True gets pickled as INT + "I01\n", and False as INT + "I00\n". Leading zeroes are never produced for a genuine integer. The 2.3 (and later) unpicklers special-case these and return bool instead; earlier unpicklers ignore the leading "0" and return the int. uBININTuJu1Push a four-byte signed integer. This handles the full range of Python (short) integers on a 32-bit box, directly as binary bytes (1 for the opcode and 4 for the integer). If the integer is non-negative and fits in 1 or 2 bytes, pickling via BININT1 or BININT2 saves space. uBININT1uKuPush a one-byte unsigned integer. This is a space optimization for pickling very small non-negative ints, in range(256). uBININT2uMuPush a two-byte unsigned integer. This is a space optimization for pickling small positive ints, in range(256, 2**16). Integers in range(256) can also be pickled via BININT2, but BININT1 instead saves a byte. uLONGuLuPush a long integer. The same as INT, except that the literal ends with 'L', and always unpickles to a Python long. There doesn't seem a real purpose to the trailing 'L'. Note that LONG takes time quadratic in the number of digits when unpickling (this is simply due to the nature of decimal->binary conversion). Proto 2 added linear-time (in C; still quadratic-time in Python) LONG1 and LONG4 opcodes. uLONG1uŠu|Long integer using one-byte length. A more efficient encoding of a Python long; the long1 encoding says it all.uLONG4u‹u~Long integer using found-byte length. A more efficient encoding of a Python long; the long4 encoding says it all.uSTRINGuSuaPush a Python string object. The argument is a repr-style string, with bracketing quote characters, and perhaps embedded escapes. The argument extends until the next newline character. (Actually, they are decoded into a str instance using the encoding given to the Unpickler constructor. or the default, 'ASCII'.) u BINSTRINGuTuPush a Python string object. There are two arguments: the first is a 4-byte little-endian signed int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. (Actually, they are decoded into a str instance using the encoding given to the Unpickler constructor. or the default, 'ASCII'.) uSHORT_BINSTRINGuUuPush a Python string object. There are two arguments: the first is a 1-byte unsigned int giving the number of bytes in the string, and the second is that many bytes, which are taken literally as the string content. (Actually, they are decoded into a str instance using the encoding given to the Unpickler constructor. or the default, 'ASCII'.) uBINBYTESuBuPush a Python bytes object. There are two arguments: the first is a 4-byte little-endian unsigned int giving the number of bytes, and the second is that many bytes, which are taken literally as the bytes content. uSHORT_BINBYTESuCuPush a Python bytes object. There are two arguments: the first is a 1-byte unsigned int giving the number of bytes, and the second is that many bytes, which are taken literally as the string content. uNONEuNuPush None on the stack.uNEWTRUEuˆu&True. Push True onto the stack.uNEWFALSEu‰u'True. Push False onto the stack.uUNICODEuVuPush a Python Unicode string object. The argument is a raw-unicode-escape encoding of a Unicode string, and so may contain embedded escape sequences. The argument extends until the next newline character. u BINUNICODEuXuPush a Python Unicode string object. There are two arguments: the first is a 4-byte little-endian unsigned int giving the number of bytes in the string. The second is that many bytes, and is the UTF-8 encoding of the Unicode string. uFLOATuFuNewline-terminated decimal float literal. The argument is repr(a_float), and in general requires 17 significant digits for roundtrip conversion to be an identity (this is so for IEEE-754 double precision values, which is what Python float maps to on most boxes). In general, FLOAT cannot be used to transport infinities, NaNs, or minus zero across boxes (or even on a single box, if the platform C library can't read the strings it produces for such things -- Windows is like that), but may do less damage than BINFLOAT on boxes with greater precision or dynamic range than IEEE-754 double. uBINFLOATuGuFloat stored in binary form, with 8 bytes of data. This generally requires less than half the space of FLOAT encoding. In general, BINFLOAT cannot be used to transport infinities, NaNs, or minus zero, raises an exception if the exponent exceeds the range of an IEEE-754 double, and retains no more than 53 bits of precision (if there are more than that, "add a half and chop" rounding is used to cut it back to 53 significant bits). u EMPTY_LISTu]uPush an empty list.uAPPENDuauAppend an object to a list. Stack before: ... pylist anyobject Stack after: ... pylist+[anyobject] although pylist is really extended in-place. uAPPENDSueuExtend a list by a slice of stack objects. Stack before: ... pylist markobject stackslice Stack after: ... pylist+stackslice although pylist is really extended in-place. uLISTulusBuild a list out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python list, which single list object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... [1, 2, 3, 'abc'] u EMPTY_TUPLEu)uPush an empty tuple.uTUPLEutuvBuild a tuple out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python tuple, which single tuple object replaces all of the stack from the topmost markobject onward. For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... (1, 2, 3, 'abc') uTUPLE1u…uBuild a one-tuple out of the topmost item on the stack. This code pops one value off the stack and pushes a tuple of length 1 whose one item is that value back onto it. In other words: stack[-1] = tuple(stack[-1:]) uTUPLE2u†uBuild a two-tuple out of the top two items on the stack. This code pops two values off the stack and pushes a tuple of length 2 whose items are those values back onto it. In other words: stack[-2:] = [tuple(stack[-2:])] uTUPLE3u‡uBuild a three-tuple out of the top three items on the stack. This code pops three values off the stack and pushes a tuple of length 3 whose items are those values back onto it. In other words: stack[-3:] = [tuple(stack[-3:])] u EMPTY_DICTu}uPush an empty dict.uDICTuduBuild a dict out of the topmost stack slice, after markobject. All the stack entries following the topmost markobject are placed into a single Python dict, which single dict object replaces all of the stack from the topmost markobject onward. The stack slice alternates key, value, key, value, .... For example, Stack before: ... markobject 1 2 3 'abc' Stack after: ... {1: 2, 3: 'abc'} uSETITEMusuAdd a key+value pair to an existing dict. Stack before: ... pydict key value Stack after: ... pydict where pydict has been modified via pydict[key] = value. uSETITEMSuuu\Add an arbitrary number of key+value pairs to an existing dict. The slice of the stack following the topmost markobject is taken as an alternating sequence of keys and values, added to the dict immediately under the topmost markobject. Everything at and after the topmost markobject is popped, leaving the mutated dict at the top of the stack. Stack before: ... pydict markobject key_1 value_1 ... key_n value_n Stack after: ... pydict where pydict has been modified via pydict[key_i] = value_i for i in 1, 2, ..., n, and in that order. uPOPu0u<Discard the top stack item, shrinking the stack by one item.uDUPu2u=Push the top stack item onto the stack again, duplicating it.uMARKu(uPush markobject onto the stack. markobject is a unique object, used by other opcodes to identify a region of the stack containing a variable number of objects for them to work on. See markobject.doc for more detail. uPOP_MARKu1uPop all the stack objects at and above the topmost markobject. When an opcode using a variable number of stack objects is done, POP_MARK is used to remove those objects, and to remove the markobject that delimited their starting position on the stack. uGETuguRead an object from the memo and push it on the stack. The index of the memo object to push is given by the newline-terminated decimal string following. BINGET and LONG_BINGET are space-optimized versions. uBINGETuhuRead an object from the memo and push it on the stack. The index of the memo object to push is given by the 1-byte unsigned integer following. u LONG_BINGETujuRead an object from the memo and push it on the stack. The index of the memo object to push is given by the 4-byte unsigned little-endian integer following. uPUTupuStore the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the newline- terminated decimal string following. BINPUT and LONG_BINPUT are space-optimized versions. uBINPUTuquStore the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the 1-byte unsigned integer following. u LONG_BINPUTuruStore the stack top into the memo. The stack is not popped. The index of the memo location to write into is given by the 4-byte unsigned little-endian integer following. uEXT1u‚uExtension code. This code and the similar EXT2 and EXT4 allow using a registry of popular objects that are pickled by name, typically classes. It is envisioned that through a global negotiation and registration process, third parties can set up a mapping between ints and object names. In order to guarantee pickle interchangeability, the extension code registry ought to be global, although a range of codes may be reserved for private use. EXT1 has a 1-byte integer argument. This is used to index into the extension registry, and the object at that index is pushed on the stack. uEXT2uƒuNExtension code. See EXT1. EXT2 has a two-byte integer argument. uEXT4u„uOExtension code. See EXT1. EXT4 has a four-byte integer argument. uGLOBALucuPush a global object (module.attr) on the stack. Two newline-terminated strings follow the GLOBAL opcode. The first is taken as a module name, and the second as a class name. The class object module.class is pushed on the stack. More accurately, the object returned by self.find_class(module, class) is pushed on the stack, so unpickling subclasses can override this form of lookup. uREDUCEuRuLPush an object built from a callable and an argument tuple. The opcode is named to remind of the __reduce__() method. Stack before: ... callable pytuple Stack after: ... callable(*pytuple) The callable and the argument tuple are the first two items returned by a __reduce__ method. Applying the callable to the argtuple is supposed to reproduce the original object, or at least get it started. If the __reduce__ method returns a 3-tuple, the last component is an argument to be passed to the object's __setstate__, and then the REDUCE opcode is followed by code to create setstate's argument, and then a BUILD opcode to apply __setstate__ to that argument. If not isinstance(callable, type), REDUCE complains unless the callable has been registered with the copyreg module's safe_constructors dict, or the callable has a magic '__safe_for_unpickling__' attribute with a true value. I'm not sure why it does this, but I've sure seen this complaint often enough when I didn't want to . uBUILDubuFinish building an object, via __setstate__ or dict update. Stack before: ... anyobject argument Stack after: ... anyobject where anyobject may have been mutated, as follows: If the object has a __setstate__ method, anyobject.__setstate__(argument) is called. Else the argument must be a dict, the object must have a __dict__, and the object is updated via anyobject.__dict__.update(argument) uINSTuiuqBuild a class instance. This is the protocol 0 version of protocol 1's OBJ opcode. INST is followed by two newline-terminated strings, giving a module and class name, just as for the GLOBAL opcode (and see GLOBAL for more details about that). self.find_class(module, name) is used to get a class object. In addition, all the objects on the stack following the topmost markobject are gathered into a tuple and popped (along with the topmost markobject), just as for the TUPLE opcode. Now it gets complicated. If all of these are true: + The argtuple is empty (markobject was at the top of the stack at the start). + The class object does not have a __getinitargs__ attribute. then we want to create an old-style class instance without invoking its __init__() method (pickle has waffled on this over the years; not calling __init__() is current wisdom). In this case, an instance of an old-style dummy class is created, and then we try to rebind its __class__ attribute to the desired class object. If this succeeds, the new instance object is pushed on the stack, and we're done. Else (the argtuple is not empty, it's not an old-style class object, or the class object does have a __getinitargs__ attribute), the code first insists that the class object have a __safe_for_unpickling__ attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE, it doesn't matter whether this attribute has a true or false value, it only matters whether it exists (XXX this is a bug). If __safe_for_unpickling__ doesn't exist, UnpicklingError is raised. Else (the class object does have a __safe_for_unpickling__ attr), the class object obtained from INST's arguments is applied to the argtuple obtained from the stack, and the resulting instance object is pushed on the stack. NOTE: checks for __safe_for_unpickling__ went away in Python 2.3. NOTE: the distinction between old-style and new-style classes does not make sense in Python 3. uOBJuouBuild a class instance. This is the protocol 1 version of protocol 0's INST opcode, and is very much like it. The major difference is that the class object is taken off the stack, allowing it to be retrieved from the memo repeatedly if several instances of the same class are created. This can be much more efficient (in both time and space) than repeatedly embedding the module and class names in INST opcodes. Unlike INST, OBJ takes no arguments from the opcode stream. Instead the class object is taken off the stack, immediately above the topmost markobject: Stack before: ... markobject classobject stackslice Stack after: ... new_instance_object As for INST, the remainder of the stack above the markobject is gathered into an argument tuple, and then the logic seems identical, except that no __safe_for_unpickling__ check is done (XXX this is a bug). See INST for the gory details. NOTE: In Python 2.3, INST and OBJ are identical except for how they get the class object. That was always the intent; the implementations had diverged for accidental reasons. uNEWOBJuuLBuild an object instance. The stack before should be thought of as containing a class object followed by an argument tuple (the tuple being the stack top). Call these cls and args. They are popped off the stack, and the value returned by cls.__new__(cls, *args) is pushed back onto the stack. uPROTOu€uProtocol version indicator. For protocol 2 and above, a pickle must start with this opcode. The argument is the protocol version, an int in range(2, 256). uSTOPu.uStop the unpickling machine. Every pickle ends with this opcode. The object at the top of the stack is popped, and that's the result of unpickling. The stack should be empty then. uPERSIDuPuPush an object identified by a persistent ID. The pickle module doesn't define what a persistent ID means. PERSID's argument is a newline-terminated str-style (no embedded escapes, no bracketing quote characters) string, which *is* "the persistent ID". The unpickler passes this string to self.persistent_load(). Whatever object that returns is pushed on the stack. There is no implementation of persistent_load() in Python's unpickler: it must be supplied by an unpickler subclass. u BINPERSIDuQuXPush an object identified by a persistent ID. Like PERSID, except the persistent ID is popped off the stack (instead of being a string embedded in the opcode bytestream). The persistent ID is passed to self.persistent_load(), and whatever object that returns is pushed on the stack. See PERSID for more detail. u%repeated name %r at indices %d and %du%repeated code %r at indices %d and %dcCstj}x$tjD]}tjd|sK|rtd|qqntt|}t|t  s|t |dkr|rtd||fqqn|j d}||kr|rtd||fn||}|j |krt d|||j fn||=qt d||fqW|rd g}x4|jD]&\}}|jd |j |fqOWt d j|ndS( Nu[A-Z][A-Z0-9_]+$u0skipping %r: it doesn't look like an opcode nameiu5skipping %r: value %r doesn't look like a pickle codeulatin-1u+checking name %r w/ code %r for consistencyuBfor pickle code %r, pickle.py uses name %r but we're using name %ruPpickle.py appears to have a pickle opcode with name %r and code %r, but we don'tu=we appear to have pickle opcodes that pickle.py doesn't have:u name %r with code %ru (ucode2opucopyupickleu__all__ureumatchuprintugetattru isinstanceubytesulenudecodeunameu ValueErroruitemsuappendujoin(uverboseucopyunameu picklecodeudumsgucode((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuassure_pickle_consistencyGs> "    uassure_pickle_consistencyccs=t|tr-ddl}|j|}nt|drH|j}n dd}x|}|jd}tj|j d}|dkr|dkrt d qt d |dkrd p||fn|j dkrd}n|j j |}|||fV|d krW|jd ks2tPqWqWdS(uxGenerate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a bytes object, it's wrapped in a BytesIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None. iNutellcSsdS(N(uNone(((u0/opt/alt/python33/lib64/python3.3/pickletools.pyusugenops..iulatin-1su#pickle exhausted before seeing STOPu!at position %s, opcode %r unknownu s.uSTOP(u isinstanceu bytes_typesuiouBytesIOuhasattrutellureaducode2opugetudecodeuNoneu ValueErroruargureaderunameuAssertionError(upickleuiougetposuposucodeuopcodeuarg((u0/opt/alt/python33/lib64/python3.3/pickletools.pyugenopsss.        c Cst}g}d}xt|D]x\}}}|dk r\|j|||fd}nd|jkr{||}}q"d|jkr"|j|q"q"Wg}d} xL|D]D\}} } ||kr| n| } |j|| | | } qW|j|| ddj|S(u7Optimize a pickle string by removing unused PUT opcodesuPUTuGETiNs(usetuNoneugenopsuappendunameuaddujoin( upugetsuputsuprevposuopcodeuarguposuprevargusuiustartustopuj((u0/opt/alt/python33/lib64/python3.3/pickletools.pyuoptimizes&    cCsng}|dkri}nd}g}d|}d} |} xt|D]\} } } | dk rtd| ddd|ndt| jdd|t|| jf}t|| j}| j }| j }t|}d}t |ks| jdkr|r|dt krt |ks.t t |krS|d t ksSt n|r|j}|dkrzd}n d |}x|d!t k r|jqW|jy|jt }Wqtk r| jdkst d }YqXqd } }n| jd"kru| dk s#t | |kr<d| } q|sKd} q|d#t krdd} q|d$|| >> import pickle >>> x = [1, 2, (3, 4), {b'abc': "def"}] >>> pkl0 = pickle.dumps(x, 0) >>> dis(pkl0) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: L LONG 1 9: a APPEND 10: L LONG 2 14: a APPEND 15: ( MARK 16: L LONG 3 20: L LONG 4 24: t TUPLE (MARK at 15) 25: p PUT 1 28: a APPEND 29: ( MARK 30: d DICT (MARK at 29) 31: p PUT 2 34: c GLOBAL '_codecs encode' 50: p PUT 3 53: ( MARK 54: V UNICODE 'abc' 59: p PUT 4 62: V UNICODE 'latin1' 70: p PUT 5 73: t TUPLE (MARK at 53) 74: p PUT 6 77: R REDUCE 78: p PUT 7 81: V UNICODE 'def' 86: p PUT 8 89: s SETITEM 90: a APPEND 91: . STOP highest protocol among opcodes = 0 Try again with a "binary" pickle. >>> pkl1 = pickle.dumps(x, 1) >>> dis(pkl1) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: K BININT1 1 6: K BININT1 2 8: ( MARK 9: K BININT1 3 11: K BININT1 4 13: t TUPLE (MARK at 8) 14: q BINPUT 1 16: } EMPTY_DICT 17: q BINPUT 2 19: c GLOBAL '_codecs encode' 35: q BINPUT 3 37: ( MARK 38: X BINUNICODE 'abc' 46: q BINPUT 4 48: X BINUNICODE 'latin1' 59: q BINPUT 5 61: t TUPLE (MARK at 37) 62: q BINPUT 6 64: R REDUCE 65: q BINPUT 7 67: X BINUNICODE 'def' 75: q BINPUT 8 77: s SETITEM 78: e APPENDS (MARK at 3) 79: . STOP highest protocol among opcodes = 1 Exercise the INST/OBJ/BUILD family. >>> import pickletools >>> dis(pickle.dumps(pickletools.dis, 0)) 0: c GLOBAL 'pickletools dis' 17: p PUT 0 20: . STOP highest protocol among opcodes = 0 >>> from pickletools import _Example >>> x = [_Example(42)] * 2 >>> dis(pickle.dumps(x, 0)) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: c GLOBAL 'copy_reg _reconstructor' 30: p PUT 1 33: ( MARK 34: c GLOBAL 'pickletools _Example' 56: p PUT 2 59: c GLOBAL '__builtin__ object' 79: p PUT 3 82: N NONE 83: t TUPLE (MARK at 33) 84: p PUT 4 87: R REDUCE 88: p PUT 5 91: ( MARK 92: d DICT (MARK at 91) 93: p PUT 6 96: V UNICODE 'value' 103: p PUT 7 106: L LONG 42 111: s SETITEM 112: b BUILD 113: a APPEND 114: g GET 5 117: a APPEND 118: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(x, 1)) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: c GLOBAL 'copy_reg _reconstructor' 29: q BINPUT 1 31: ( MARK 32: c GLOBAL 'pickletools _Example' 54: q BINPUT 2 56: c GLOBAL '__builtin__ object' 76: q BINPUT 3 78: N NONE 79: t TUPLE (MARK at 31) 80: q BINPUT 4 82: R REDUCE 83: q BINPUT 5 85: } EMPTY_DICT 86: q BINPUT 6 88: X BINUNICODE 'value' 98: q BINPUT 7 100: K BININT1 42 102: s SETITEM 103: b BUILD 104: h BINGET 5 106: e APPENDS (MARK at 3) 107: . STOP highest protocol among opcodes = 1 Try "the canonical" recursive-object test. >>> L = [] >>> T = L, >>> L.append(T) >>> L[0] is T True >>> T[0] is L True >>> L[0][0] is L True >>> T[0][0] is T True >>> dis(pickle.dumps(L, 0)) 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 0 5: ( MARK 6: g GET 0 9: t TUPLE (MARK at 5) 10: p PUT 1 13: a APPEND 14: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(L, 1)) 0: ] EMPTY_LIST 1: q BINPUT 0 3: ( MARK 4: h BINGET 0 6: t TUPLE (MARK at 3) 7: q BINPUT 1 9: a APPEND 10: . STOP highest protocol among opcodes = 1 Note that, in the protocol 0 pickle of the recursive tuple, the disassembler has to emulate the stack in order to realize that the POP opcode at 16 gets rid of the MARK at 0. >>> dis(pickle.dumps(T, 0)) 0: ( MARK 1: ( MARK 2: l LIST (MARK at 1) 3: p PUT 0 6: ( MARK 7: g GET 0 10: t TUPLE (MARK at 6) 11: p PUT 1 14: a APPEND 15: 0 POP 16: 0 POP (MARK at 0) 17: g GET 1 20: . STOP highest protocol among opcodes = 0 >>> dis(pickle.dumps(T, 1)) 0: ( MARK 1: ] EMPTY_LIST 2: q BINPUT 0 4: ( MARK 5: h BINGET 0 7: t TUPLE (MARK at 4) 8: q BINPUT 1 10: a APPEND 11: 1 POP_MARK (MARK at 0) 12: h BINGET 1 14: . STOP highest protocol among opcodes = 1 Try protocol 2. >>> dis(pickle.dumps(L, 2)) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: h BINGET 0 7: \x85 TUPLE1 8: q BINPUT 1 10: a APPEND 11: . STOP highest protocol among opcodes = 2 >>> dis(pickle.dumps(T, 2)) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: h BINGET 0 7: \x85 TUPLE1 8: q BINPUT 1 10: a APPEND 11: 0 POP 12: h BINGET 1 14: . STOP highest protocol among opcodes = 2 Try protocol 3 with annotations: >>> dis(pickle.dumps(T, 3), annotate=1) 0: \x80 PROTO 3 Protocol version indicator. 2: ] EMPTY_LIST Push an empty list. 3: q BINPUT 0 Store the stack top into the memo. The stack is not popped. 5: h BINGET 0 Read an object from the memo and push it on the stack. 7: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. 8: q BINPUT 1 Store the stack top into the memo. The stack is not popped. 10: a APPEND Append an object to a list. 11: 0 POP Discard the top stack item, shrinking the stack by one item. 12: h BINGET 1 Read an object from the memo and push it on the stack. 14: . STOP Stop the unpickling machine. highest protocol among opcodes = 2 u= >>> import pickle >>> import io >>> f = io.BytesIO() >>> p = pickle.Pickler(f, 2) >>> x = [1, 2, 3] >>> p.dump(x) >>> p.dump(x) >>> f.seek(0) 0 >>> memo = {} >>> dis(f, memo=memo) 0: \x80 PROTO 2 2: ] EMPTY_LIST 3: q BINPUT 0 5: ( MARK 6: K BININT1 1 8: K BININT1 2 10: K BININT1 3 12: e APPENDS (MARK at 5) 13: . STOP highest protocol among opcodes = 2 >>> dis(f, memo=memo) 14: \x80 PROTO 2 16: h BINGET 0 18: . STOP highest protocol among opcodes = 2 udisassembler_testudisassembler_memo_testcCsddl}|jS(Ni(udoctestutestmod(udoctest((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu_test s u_testu__main__u descriptionu$disassemble one or more pickle filesu pickle_fileutypeubrunargsu*uhelputhe pickle fileu-ou--outputudefaultuwu+the file where the output should be writtenu-mu--memouactionu store_trueu#preserve memo between disassembliesu-lu --indentlevelu8the number of blanks by which to indent a new MARK levelu-au --annotateu2annotate each line with a short opcode descriptionu-pu --preambleu==> {name} <==uMif more than one pickle file is specified, print this before each disassemblyu-tu--testurun self-test suiteu-vu)run verbosely; only affects self-test runiu (}u__doc__ucodecsupickleureusysu__all__u bytes_typesu UP_TO_NEWLINEuTAKEN_FROM_ARGUMENT1uTAKEN_FROM_ARGUMENT4uTAKEN_FROM_ARGUMENT4UuobjectuArgumentDescriptorustructuunpacku_unpacku read_uint1uuint1u read_uint2uuint2u read_int4uint4u read_uint4uuint4uTrueu read_stringnlustringnluread_stringnl_noescapeustringnl_noescapeuread_stringnl_noescape_pairustringnl_noescape_pairu read_string4ustring4u read_string1ustring1u read_bytes1ubytes1u read_bytes4ubytes4uread_unicodestringnluunicodestringnluread_unicodestring4uunicodestring4uread_decimalnl_shorturead_decimalnl_longudecimalnl_shortudecimalnl_longu read_floatnlufloatnlu read_float8ufloat8u decode_longu read_long1ulong1u read_long4ulong4u StackObjectuintupyintupylonguboolupyinteger_or_boolupyboolufloatupyfloatubytesupystringupybytesustru pyunicodeutypeuNoneupynoneutupleupytupleulistupylistudictupydictu anyobjectu markobjectu stacksliceu OpcodeInfouIuopcodesuname2iucode2iu enumerateuiudunameu ValueErrorucodeucode2opuFalseuassure_pickle_consistencyugenopsuoptimizeudisu_Exampleu _dis_testu _memo_testu__test__u_testu__name__uargparseuArgumentParseruparseru add_argumentuFileTypeustdoutu parse_argsuargsutestuannotateu pickle_fileu print_helpulenuoutputu indentlevelumemoufupreambleuformatuwrite(((u0/opt/alt/python33/lib64/python3.3/pickletools.pyu s     #        /                                               ;                                                                                                               +                    & 8        !