Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between __reduce__ and __reduce_ex__?

Tags:

python

pickle

I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?

like image 704
Moe Avatar asked Sep 29 '08 19:09

Moe


People also ask

What is __ Reduce_ex __ in Python?

object.__reduce_ex__(protocol) It takes a single integer argument. The main use for this method is to provide backwards-compatible reduce values for older Python releases.

What is the use of pickling in Python?

Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it's the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network.


2 Answers

The docs say that

If provided, at pickling time __reduce__() will be called with no arguments, and it must return either a string or a tuple.

On the other hand,

It is sometimes useful to know the protocol version when implementing __reduce__. This can be done by implementing a method named __reduce_ex__ instead of __reduce__. __reduce_ex__, when it exists, is called in preference over __reduce__ (you may still provide __reduce__ for backwards compatibility). The __reduce_ex__ method will be called with a single integer argument, the protocol version.

On the gripping hand, Guido says that this is an area that could be cleaned up.

like image 192
Adriano Varoli Piazza Avatar answered Sep 20 '22 13:09

Adriano Varoli Piazza


__reduce_ex__ is what __reduce__ should have been but never became. __reduce_ex__ works like __reduce__ but the pickle protocol is passed.

like image 26
Armin Ronacher Avatar answered Sep 21 '22 13:09

Armin Ronacher