Special Method Protocols
__reduce_ex__() — serialization protocol
Provide a protocol-aware reduction recipe. Pickle prefers __reduce_ex__ when available; choose a compatible representation for the protocol. Only deserialize trusted data. The compact example intentionally reconstructs a string surrogate rather than the original class.
Formal Syntax & Structure
python syntaxpython
def __reduce_ex__(self, protocol):Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| protocol | int | Serialization protocol number. |
Return Value
str | tuple
Reduction recipe.
Working Example
Example Snippetpython
import pickleclass Label: def __reduce_ex__(self, protocol): return (str,(f"protocol {protocol}",))print(pickle.loads(pickle.dumps(Label(), protocol=4)))