The opcodes page lists what each opcode
does. This page gives the rules around them: which protocol came with which Python, how a
stream is framed, how out-of-band buffers, persistent IDs, extension codes and the memo
work, and how objects are rebuilt. Sources, all read on 2026-11-14:
Lib/pickle.py,
Lib/pickletools.py
and Lib/copyreg.py
from the main branch, and
PEP 307,
PEP 3154 and
PEP 574 as raw text. Behaviour described
as what “the pickler” or “the unpickler” does is that of the pure-Python classes in
pickle.py; where the C accelerator
(Modules/_pickle.c)
differs, its rules are given separately.
Protocols
| Protocol | Python | What it adds | Source |
|---|---|---|---|
| 0 | Before 2.3; named retroactively | Text mode: printable bytes only. Format version 1.0, and 1.1 with INST added. | PEP 307; compatible_formats in pickle.py |
| 1 | Before 2.3; named retroactively | Binary mode: the BIN… opcodes, EMPTY_…, MARK-based APPENDS and SETITEMS, OBJ. Format versions 1.2, and 1.3 with BINFLOAT added. | PEP 307; compatible_formats |
| 2 | 2.3 | PROTO, NEWOBJ, the extension registry (EXT1/2/4), TUPLE1/2/3, NEWTRUE/NEWFALSE, LONG1/LONG4. A superset of protocol 1, but the first opcode names the protocol so later protocols need not be supersets. | PEP 307 (header: Python-Version 2.3) |
| 3 | 3.0 | bytes support: BINBYTES, SHORT_BINBYTES. “Unicode strings by default and the new bytes object.” | PEP 3154 (rationale); pickletools.py |
| 4 | 3.4 | Framing (FRAME), STACK_GLOBAL and dotted names, 8-byte lengths (BINUNICODE8, BINBYTES8), SHORT_BINUNICODE, sets (EMPTY_SET, ADDITEMS, FROZENSET), NEWOBJ_EX, MEMOIZE. | PEP 3154 (header: Python-Version 3.4) |
| 5 | 3.8 | BYTEARRAY8, NEXT_BUFFER, READONLY_BUFFER for out-of-band buffers. “Incompatible with previous versions.” | PEP 574 (header: Python-Version 3.8); docstring of Pickler |
- Default and highest. In the main branch
HIGHEST_PROTOCOL = 5andDEFAULT_PROTOCOL = 5(pickle.py). The comment says the default may be lower than the highest, and should be raised only when the oldest supported Python already includes it.format_versionis"5.0". PEP 307 added the rule that a negative protocol selects the highest one. - Choosing a protocol.
Nonemeans the default; a negative number means the highest; a number from 0 to the highest is used; anything else raisesValueError("pickle protocol must be <= 5"). The pickler writesPROTOonly for protocol 2 and up (dump). It also uses the binary opcodes from protocol 1 (bin = protocol >= 1). - PROTO range. The unpickler accepts a
PROTOargument of 0 to 5 and otherwise raisesValueError("unsupported pickle protocol: n")(load_proto); the value is then kept as the stream’s protocol, which later affectsfind_class(see name mapping). Thepickletoolsdocumentation says instead that the argument is “an int in range(2, 256)”, so the two sources differ on the lower bound; no pickler writesPROTObelow 2. - Reading without a protocol. The unpickler starts with protocol 0 and does not need it announced: protocol 0 and 1 streams have no
PROTOand the same machine runs all of them (PEP 307). - Compatibility. Pickles written under protocol N cannot be read by versions of Python older than the one that introduced N (PEP 307).
Frames (protocol 4 and later)
After PROTO 4 the pickler starts framing (start_framing in dump). The structure from PEP 3154 is: 80 04, then for each frame the FRAME opcode 95, an 8-byte little-endian frame size, and that many bytes of opcodes. The last frame is simply the one that ends with STOP; there is no last-frame marker.
- Target size.
_FRAME_SIZE_TARGET = 64 * 1024. Before each object is saved the pickler checks the current frame (commit_frame) and closes it once it has reached 64 KiB or more. PEP 3154 calls the partition into frames an implementation detail and gives closing at about 64 KiB as a reasonable choice. - Minimum frame.
_FRAME_SIZE_MIN = 4: a frame shorter than 4 bytes is written without aFRAMEheader, as plain opcodes. A frame is also closed with force at the end ofdump. - Large objects stay outside frames. A
bytes,bytearrayor encodedstrof 64 KiB or more (and any over 4 GiB, which must use the 8-byte opcodes) is written bywrite_large_bytes: it closes the current frame, then writes the opcode header and the payload directly, with noFRAMEin front, “to make it possible to optimize file.read calls in the loader”. - No opcode may straddle frames. PEP 3154: “it is forbidden for a pickle opcode to straddle frame boundaries. The pickler takes care not to produce such pickles, and the unpickler refuses them.” The pure-Python
_UnframerraisesUnpicklingError("pickle exhausted before end of frame")when a read or line runs past the frame end, andUnpicklingError("beginning of a new frame before end of current frame")if a newFRAMEappears while the current frame has unread bytes. When a frame is used up, reading falls back to the file itself. - Size limits.
load_framereads the 8-byte size; a size abovesys.maxsizeraisesValueError("frame size > sys.maxsize"); a file that ends before the frame’s bytes raisesEOFError. Reads are done in chunks of at most 1 MiB (_MIN_READ_BUF_SIZE) to avoid over-allocating for a hostile size.
Out-of-band buffers (protocol 5)
PEP 574 lets large buffers (such as array data) travel outside the pickle stream, to avoid copies. The type is pickle.PickleBuffer (_pickle, when available); raw() returns a memoryview of its raw bytes and release() makes it unusable.
- Pickler side.
Pickler(file, protocol, buffer_callback=…). Ifbuffer_callbackis notNoneand the protocol is below 5,ValueError("buffer_callback needs protocol >= 5")is raised. PEP 574 words the error as “protocol is None or smaller than 5”, but in the main branchNoneis first replaced by the default, 5, so only an explicit protocol below 5 fails. - Which buffers. A type’s
__reduce_ex__returns aPickleBufferinside its arguments, as inreturn type(self), (PickleBuffer(self),), None. Pickling aPickleBufferwith protocol below 5 raisesPicklingError("PickleBuffer can only be pickled with protocol >= 5"); a buffer that is not contiguous raisesPicklingError("PickleBuffer can not be pickled when pointing to a non-contiguous buffer"). Only the raw data is considered; shape or type information must be returned separately. - In-band or out-of-band. With no callback the buffer is in-band. With a callback it is called with the buffer: a true result keeps the buffer in-band; a false result (such as
None) makes it out-of-band. The callback must keep the buffers in order. - In-band form. A writable buffer is written as
BYTEARRAY8(like abytearray), a read-only one asBINBYTES/SHORT_BINBYTES/BINBYTES8(likebytes), and the object is memoized. - Out-of-band form. A writable buffer is the single opcode
NEXT_BUFFER; a read-only one isNEXT_BUFFERfollowed byREADONLY_BUFFER. Nothing is memoized for it. - Unpickler side.
Unpickler(file, buffers=…)takes an iterable that is consumed in order, one item perNEXT_BUFFER.READONLY_BUFFERreplaces the top item withmemoryview(buf).toreadonly()if it is writable. Errors:NEXT_BUFFERwithbuffers=NoneraisesUnpicklingError("pickle stream refers to out-of-band data but no *buffers* argument was given"); running out raisesUnpicklingError("not enough out-of-band buffers"). PEP 574: it is an error forbuffersto beNoneif the stream was produced with a callback that took buffers out. - Example.
data = pickle.dumps(a, protocol=5, buffer_callback=buffers.append)thenpickle.loads(data, buffers=buffers)(from PEP 574).
Persistent IDs
A persistent ID names an object that is stored outside the pickle. The module does not define what the ID means.
- Pickler hook.
persistent_id(obj), overridden in a subclass; the default returnsNone. It is called first for every object that is saved, before the memo is checked. A return other thanNoneis the persistent ID, and the object is not saved by value. - What is written. Protocol 0:
PERSIDandstr(pid)encoded as ASCII, then a newline; if that is not ASCII,PicklingError("persistent IDs in protocol 0 must be ASCII strings"). Protocol 1 and later: the ID is saved as an ordinary object (with persistent-ID lookup switched off for it), thenBINPERSID. The ID can therefore be any picklable object. - Unpickler hook.
persistent_load(pid), supplied by a subclass. The default raisesUnpicklingError("unsupported persistent id encountered").PERSIDreads a line, decodes it as ASCII (UnpicklingError("persistent IDs in protocol 0 must be ASCII strings")on failure) and pushes the result ofpersistent_load;BINPERSIDpops the ID from the stack and pushes the result.
Extension registry
From protocol 2, a global name that is registered with a small number is written as EXT1, EXT2 or EXT4 instead of the module and name. The registry is in copyreg (PEP 307); the codes are meant to be global, so that a pickle does not depend on context.
- Registering.
copyreg.add_extension(module, name, code)accepts codes from 1 to 0x7FFFFFFF (ValueError("code out of range")otherwise). Registering the same pair and code again is allowed; a name already registered with another code, or a code already used for another name, raisesValueError.remove_extensionis for testing andclear_extension_cacheempties the loader’s cache. - Reserved ranges (comment in
copyreg.py; codes are assigned by the Python Software Foundation):First Last Purpose 1 127 Python standard library 128 191 Zope 192 239 Third parties 240 255 Private use (never assigned) 256 no end Future assignment - Which opcode is written.
save_globallooks up(module, name)first. A code up to 0xFF isEXT1(one byte); up to 0xFFFFEXT2(two bytes, unsigned); larger codesEXT4(four bytes, signed). Code 0 is never written (RuntimeError("extension code 0 is out of range")). PEP 307: codes 1 to 255 take two bytes including the opcode, 256 to 65535 take three. - Loading. The unpickler first checks a cache of already resolved codes. Otherwise it looks the code up in the registry and resolves it with
find_class. An unknown code of 0 or below raisesUnpicklingError("EXT specifies code <= 0")(“corrupt or hostile”); an unknown positive code raisesValueError("unregistered extension code n").
The memo
- What is memoized. The pickler keeps a dictionary from each saved object’s identity to its memo index and the object (it keeps the object alive). Before saving anything it looks there, and if found writes a
GETinstead, so shared and recursive objects are written once. Memoized after being written:str,bytes(protocol 3 and up),bytearray(protocol 5), non-empty tuples, lists, dicts, sets, frozensets, globals saved by name, objects built bysave_reduceand in-band buffers. Not memoized:None, bools, ints, floats, the empty tuple, and extension codes. - Index. The index is the current size of the memo, so indices run 0, 1, 2, … in order of memoization. This is a convention that lets the unpickler use a plain growable array.
- Which opcode. Protocol 0 writes
PUTwith the index as decimal text and a newline. Protocols 1 to 3 writeBINPUTwith a 1-byte index below 256, otherwiseLONG_BINPUTwith a 4-byte unsigned index. Protocol 4 and later writeMEMOIZEwith no argument; the index is the memo length at that moment.GET,BINGETandLONG_BINGETfollow the same choice (GETfor protocol 0, 1-byte index below 256, else 4 bytes). - No pop. The
PUTfamily andMEMOIZEcopy the top of the stack into the memo and leave it there. - Unpickler errors.
GET,BINGETorLONG_BINGETof an index never stored raisesUnpicklingError("Memo value not found at index n"). A negativePUTorBINPUTindex raisesValueError, as does aLONG_BINPUTindex abovesys.maxsize. APUTmay store at any index (the memo is a dictionary); inpickle.pyMEMOIZEuses the dictionary’s length (the C unpickler counts differently with sparse indices: see the C accelerator). - Per stream. Memo indices belong to one stream. A reused
Picklerkeeps its memo betweendumpcalls unlessclear_memo()is called; a pickler with thefastflag set does not memoize at all (memoizereturns at once). - Recursive tuples and frozensets. They cannot be created before their items. If saving the items has memoized the object already, the pickler throws away what it pushed and writes a
GETof the memoized one, afterPOPs (protocol 0),POP_MARK(protocol 1 and up) orPOP× n (a protocol 2 tuple of 1 to 3 items). The same happens insave_reduce: if the object is already in the memo, it writesPOPandGET.
Building objects: __reduce_ex__ and BUILD
How the pickler picks a method
For each object, in this order in pickle.py (Pickler.save; the C pickler consults reducer_override later, see the C accelerator): the persistent ID hook; the memo; the optional reducer_override method (a result of NotImplemented falls through); the type’s own save routine for exact built-in types (None, bool, int, float, bytes, bytearray, PickleBuffer, str, tuple, list, dict, set, frozenset, functions, type); the pickler’s dispatch_table, or else copyreg.dispatch_table; classes with a custom metaclass, saved as globals; obj.__reduce_ex__(protocol); obj.__reduce__(). If none exists, PicklingError("Can't pickle … object").
The returned tuple
It is a string or a tuple of 2 to 6 items; any other result raises PicklingError. A string means “save as a global by this name” (save_global(obj, name)). Items past the second may be None.
| Item | Name | What it does | Opcodes written |
|---|---|---|---|
| 1 | callable | Called to create the initial object. Must be callable (PicklingError otherwise). | Saved first, see below |
| 2 | args | A tuple of arguments (PicklingError if not a tuple). | Saved next, then REDUCE |
| 3 | state | State to apply after creation. | The state, then BUILD |
| 4 | listitems | An iterator of items to append. | APPEND per item (protocol 0), or in batches of up to 1000: MARK items APPENDS, or APPEND for a batch of one |
| 5 | dictitems | An iterator of (key, value) pairs. | SETITEM per pair (protocol 0), or in batches of 1000: MARK pairs SETITEMS |
| 6 | state_setter | A callable f(obj, state) used instead of BUILD. | setter, obj (a GET), state, TUPLE2, REDUCE, POP |
The order of writing is: callable and args (with REDUCE or the special forms below), memoize the object, list items, dict items, then the state (BUILD, or the state-setter sequence). The object is memoized after its arguments are saved and before its state, so the state may refer back to it.
Special callables
__newobj__. If protocol is 2 or more and the callable’s__name__is__newobj__, the pickler assumes the semanticscls.__new__(cls, *args)and writes the class (args[0]), the remaining arguments as a tuple, andNEWOBJ, without pickling a reference to__newobj__. The first argument must have__new__and be the object’s own class, orPicklingError. With protocol 0 or 1 a reference to__newobj__is pickled as an ordinary callable and used withREDUCE(PEP 307).__newobj_ex__. Protocol 4 and later: class, args tuple, kwargs dict, thenNEWOBJ_EX. Protocols 2 and 3 cannot express keywords, so it savesfunctools.partial(cls.__new__, cls, *args, **kwargs), an empty tuple andREDUCE.- Default object reduction.
copyreg.__newobj__and__newobj_ex__are the standard implementations of those two names. For protocols 0 and 1copyreg._reduce_exbuilds(_reconstructor, (cls, base, state), dict)(_reconstructorcallsobject.__new__(cls)or the base type’s__new__). A class with__slots__and no__getstate__cannot be pickled with protocol 0 or 1. - NEWOBJ and REDUCE.
NEWOBJcallscls.__new__(cls, *args)directly;REDUCEcalls an arbitrary callable.INSTandOBJare never written bypickle.pybut are still read.
INST and OBJ when loading
Both gather the items above the mark as arguments. If the arguments are empty, the class is a type and has no __getinitargs__, the instance is made with klass.__new__(klass) without calling __init__; otherwise klass(*args) is called. INST finds its class by the module and name on the line (through find_class); OBJ takes the class from just above the mark, so it can come from the memo. The old __safe_for_unpickling__ checks no longer exist (PEP 307, pickletools notes).
BUILD
BUILD pops state and applies it to the object now on top:
- If the object has
__setstate__, it is called with the state and that is all. - Otherwise, a state that is a 2-tuple is split into a state and a slotstate.
- A non-empty state is a dictionary merged into the object’s
__dict__(string keys are interned). - A non-empty slotstate is a dictionary applied with
setattr(obj, name, value)for each item.
Steps 3 and 4 are pickle.py, which ignores any false state. The C unpickler requires the state to be None or a dictionary and a slot state to be a dictionary, otherwise UnpicklingError (C accelerator rules).
PEP 307 gives the default state for a new-style class: None with neither __dict__ nor __slots__; the instance dictionary with a __dict__; a pair (dictionary, slot values) with both; (None, slot values) with __slots__ only. A None state is not pickled, so __setstate__ is not called for it.
Other loader rules
REDUCEpops the argument tuple and replaces the callable below it withfunc(*args).POPon an empty stack discards the current mark’s sub-stack instead.MARKsaves the current stack on a meta-stack and starts a new, empty one; the “slice after the mark” opcodes take that whole new stack and restore the old one.STACK_GLOBALrequires both popped items to be exactlystr, otherwiseUnpicklingError("STACK_GLOBAL requires str").STOPpops the top of the stack as the result. Reaching the end of the stream without it raisesEOFError.
Text, integers and encodings
How the pickler picks integer opcodes
| Condition (protocol 1 and up) | Opcode |
|---|---|
| 0 to 255 | BININT1 |
| 256 to 65535 | BININT2 |
| −231 to 231−1 (the rest) | BININT |
| Larger, protocol 2 and up, encoded length below 256 bytes | LONG1 |
| Larger, protocol 2 and up, longer | LONG4 |
Protocol 0 writes INT and the decimal digits for the 4-byte signed range, otherwise LONG with the digits and a trailing L. The long encoding is little-endian two’s complement in the fewest bytes, with 0 as zero bytes (encode_long).
Other values
- Bools. Protocol 2 and up:
NEWTRUE,NEWFALSE. Before that:INTwith the lines01and00(I01andI00); the unpickler turns exactly these lines into True and False. - Floats. Protocol 1 and up:
BINFLOAT, 8 bytes big-endian. Protocol 0:FLOATwithrepr(x).pickletoolswarns that neither can carry infinities, NaNs or minus zero portably (FLOATdepends on the platform’s C library), and thatBINFLOATraises an exception for an exponent beyond an IEEE-754 double and keeps no more than 53 bits. - Tuples. Protocol 2 and up:
TUPLE1,TUPLE2orTUPLE3for 1 to 3 items; other non-empty tuplesMARKitemsTUPLE. The empty tuple isEMPTY_TUPLEfrom protocol 1,MARK TUPLEin protocol 0. Lists and dicts similarly useEMPTY_LIST/EMPTY_DICTfrom protocol 1 andMARK LIST/MARK DICTin protocol 0. - Sets. Protocol 4 and up:
EMPTY_SETthen, in batches of 1000,MARKitemsADDITEMS; frozensetsMARKitemsFROZENSET. Earlier:set(list)andfrozenset(list)byREDUCE. - Bytes. Protocol 3 and up:
SHORT_BINBYTESup to 255 bytes;BINBYTESup to 4 GiB;BINBYTES8above that (protocol 4). Below protocol 3 an empty bytes isbytes()and otherscodecs.encode(text, 'latin1')viaREDUCE. AbytearrayisBYTEARRAY8in protocol 5, otherwisebytearray(bytes)byREDUCE. - Strings. Protocol 1 and up: UTF-8 with
surrogatepass, asSHORT_BINUNICODE(up to 255 bytes, protocol 4 and up),BINUNICODE, orBINUNICODE8above 4 GiB (protocol 4). Protocol 0:UNICODE, a raw-unicode-escape line, in which the pickler first replaces backslash, NUL, line feed, carriage return and Ctrl-Z by the six-character escapes\u005c,\u0000,\u000a,\u000dand\u001a.
Reading text opcodes
STRING. The argument line must start and end with the same quote,'or", which are stripped (otherwiseUnpicklingError("the STRING opcode argument must be quoted")). The rest is decoded withcodecs.escape_decode, so backslash escapes (\n,\x41, octal and so on) work as in a Python 2repr. It is then decoded with the unpickler’sencoding(defaultASCII) anderrors(defaultstrict), or kept asbytesif the encoding is'bytes'. These are Python 2strvalues;pickle.pyno longer writesSTRING.BINSTRING,SHORT_BINSTRING. The same decoding applies.BINSTRINGhas a signed 4-byte length; a negative one raisesUnpicklingError("BINSTRING pickle has negative byte count").LONG4. A negative length raisesUnpicklingError("LONG pickle has negative byte count").INTandLONG.INTaccepts the lines00and01as booleans and otherwiseint()of the line. ForLONG, the trailingLis optional on loading (it is removed if present); it is always written.- Binary strings and bytes.
BINUNICODE,SHORT_BINUNICODEandBINUNICODE8are UTF-8 decoded withsurrogatepass. A length abovesys.maxsizeraisesUnpicklingError("… exceeds system's maximum size")forBINBYTES,BINBYTES8,BINUNICODE,BINUNICODE8andBYTEARRAY8. GLOBAL. Two lines, decoded as UTF-8;INSTdecodes its lines as ASCII. When writing, protocol 3 and up use UTF-8 and lower protocols ASCII, so a non-ASCII module or name raisesPicklingErrorwith protocols 0 to 2.
The C accelerator: validity rules that differ from pickle.py
CPython’s default pickle.Pickler and pickle.Unpickler are the
C implementation, Modules/_pickle.c. It reads and writes the same opcodes
and arguments as Lib/pickle.py (the rules above), but it enforces more
conditions on a stream. Everything below is read from the raw _pickle.c and
pickle.py of the CPython main branch, and is stated as what a
valid stream must satisfy for the C loader; pickle.py is more lenient where
noted. Message texts are given only to name the rule.
Loader
- Opcode byte. Any byte that is not one of the 68 opcodes is an error:
UnpicklingError("invalid load key, 'c'.")(a printable byte other than'and backslash is shown as itself, any other byte as\xhh).pickle.pyraisesKeyErrorfor it. - Stack and marks. Every opcode that takes items off the stack may take only items pushed after the innermost open
MARK(the “fence”); taking more isUnpicklingError(“unpickling stack underflow”, or “unexpected MARK found” when a mark is open). An opcode that needs a mark and finds none, such asTUPLE,LIST,DICT,APPENDS,SETITEMS,POP_MARK,INST,OBJ,FROZENSETandADDITEMS, raisesUnpicklingError("could not find MARK").POPwith nothing above the innermost mark discards that mark, as inpickle.py. Running out of input beforeSTOPisEOFError. DICT. The number of items above the mark must be even:UnpicklingError("odd number of items for DICT").pickle.pyfails withIndexError.SETITEMS. The same: an odd number of items above the mark isUnpicklingError("odd number of items for SETITEMS"), and the object below the mark must exist and accept__setitem__(it need not be adict).BUILD. If the object has__setstate__it is called with the state and nothing else is checked. Otherwise: a state that is a tuple of exactly 2 items is always split into a state and a slot state; the state must beNone(ignored) or a dictionary, otherwiseUnpicklingError("state is not a dictionary")(pickle.pyskips any false state, such as 0,''or[], and needs.itemson a true one); a slot state, if present (evenNone), must be a dictionary, otherwiseUnpicklingError("slot state is not a dictionary"), and each item is applied withsetattr(pickle.pyskips a false slot state). Dictionary keys of the state that are exactlystrare interned before being stored in__dict__.NEWOBJandNEWOBJ_EX. After popping the class, the argument tuple and (for_EX) the keyword dictionary: the class must be a type (PyType_Check) and have atp_newslot (“doesn’t have __new__”); the arguments must be atuple; forNEWOBJ_EXthe keywords must be adict; otherwiseUnpicklingError. The object is then made by callingtp_new(cls, args, kwargs)directly.pickle.pychecks none of this (it callscls.__new__(cls, *args, **kwargs)).- Memo indices. A
GETfamily opcode for an index never stored isUnpicklingError("Memo value not found at index n").MEMOIZEstores at memo_len, the number of memo array slots filled so far. APUTwhose index is beyond the allocated array and more than twice memo_len is kept in a side dictionary and is not counted, so a stream that mixes such sparsePUTs withMEMOIZEgets a different index frompickle.py, whereMEMOIZEuses the length of the memo dictionary. Streams from either pickler number their entries 0, 1, 2, … and read the same in both. A negative argument ofLONG_BINPUTis aValueError. - Size limits. The 8-byte lengths of
BINBYTES8,BINUNICODE8andBYTEARRAY8and the 4-byte lengths ofBINBYTESandBINUNICODE, and the size of aFRAME, above what fits inPy_ssize_traiseOverflowErrorhere (pickle.pygivesUnpicklingErrororValueError). - Persistent IDs. Without a
persistent_loadmethod,PERSIDandBINPERSIDraiseUnpicklingErrorwith the message “A load persistent id instruction was encountered, but no persistent_load function was specified.” (pickle.py: “unsupported persistent id encountered”).
Pickler
- Order of saving. In the C pickler the exact built-in types are saved by their own routines before
reducer_overrideis asked: first, with no memo check,None, bools, exactintand exactfloat; then, after the memo check, exactbytesandstr, exactweakref.ref, and exactdict,set,frozenset,list,tuple,bytearrayandPickleBuffer. Only then isreducer_overridecalled (a result ofNotImplementedfalls through totype, functions,dispatch_table,__reduce_ex__and__reduce__). Soreducer_overridenever sees an exact instance of those types.pickle.pycallsreducer_overridefirst, for every object that is not in the memo. - Reduce values. As in
pickle.pya result must be a string or a tuple of 2 to 6 items; the C pickler also checks the callable is callable, the arguments are a tuple, a list-items value is an iterator orNone, a dict-items value an iterator orNone, and a state setter callable orNone. Under__newobj__there must be at least one argument, the first must be a class and, when the object being saved is known, the object’s own class; under__newobj_ex__there must be exactly three arguments (a class, a tuple and a dict). Each failure is aPicklingError.
Weak references
Both picklers on the CPython main branch (save_weakref in pickle.py and _pickle.c) pickle an exact weakref.ref (not weakref.proxy or a subclass) by reconstruction. Nothing special is added to the byte grammar: the opcodes are those of REDUCE.
- Live reference. The pickler saves the global
weakref.ref(the reference’s type), then, below protocol 2 only,MARK; then the referent (saved “weakly”: see below); thenTUPLE1(protocol 2 and later) orTUPLE(below 2); thenREDUCE; then the memo write for the reference. If saving the referent already pickled this same reference (a cycle), the pickler writesPOPand aGETof the existing memo entry instead of a new memo write. - Dead reference. A reference whose referent has gone is written as the bytes
GLOBALweakref\n_dead_ref\n(all dead references are interchangeable) and is not memoized. - Validity rule. A referent that is reachable in the stream only through weak references would be collected the moment the stream is loaded. The pickler tracks this (a referent first saved by
save_weakrefis flagged “weak-only” until some ordinary save of it) and, if any flag is left when the top-level object has been saved, raisesPicklingError(“cannot pickle weak reference(s) whose referent(s) have no strong reference in the pickle”) instead of writingSTOP. A written pickle therefore never holds a weak-only referent. - Loading is plain
REDUCE(andGLOBAL), withfind_classresolvingweakref.refandweakref._dead_ref.
Dotted names (protocol 4)
A global’s name is its __qualname__ (for example Outer.Inner.method), as PEP 3154 proposed via PEP 3155. STACK_GLOBAL carries the module and the qualified name as two strings, and the unpickler resolves the dots in turn with getattr (find_class: when the stream’s protocol is 4 or more and the name contains a dot, it walks the path; failure raises AttributeError("Can't resolve path … on module …")). Below protocol 4 the pickler instead writes a chain: for a.b.c it saves getattr twice and the top-level object a, then each attribute name with TUPLE2 (TUPLE between MARKs in protocol 0 and 1) and REDUCE.
- Names containing
<locals>(a function defined inside another) raisePicklingError("Can't pickle local object"). - Private names are mangled: a part that starts with two underscores and does not end with two is written as
_Class__name, using the preceding part with leading underscores removed. - The module is the object’s
__module__; if it has none,sys.modulesis searched for the object, defaulting to__main__. If the name cannot be found there, or finds a different object,PicklingErrorsays so. - Python 2 names are renamed when reading or writing protocols below 3; see Python 2 name mapping.