Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pickling keyword arguments in Python 3

Python 2 doc says:

Deprecated since version 2.3: Use function(*args, **keywords) instead of apply(function, args, keywords) (see Unpacking Argument Lists).

Pickle module requires the following syntax to define __reduce__ method to dump an object:

def __reduce__():
     return (<A callable object>, <A tuple of arguments for the callable object.>) 

(I know that the length of tuple returned from __reduce__ can be >2 but needs to be <=5. Considering the case of length 2 in the context of current question.)

This means it is not possible to pass keyword arguments to the callable object. In Python 2, I have the following work-around:

def __reduce__():
     return (apply, (<A callable object>, ((<args>,), <kwargs>))

However, builtins.apply has been removed in Python 3. Is there any other alternative to implementing my own version of builtins.apply in Python 3?

like image 746
Saim Raza Avatar asked Feb 21 '19 08:02

Saim Raza


People also ask

How do you use pickle in Python 3?

First, import pickle to use it, then we define an example dictionary, which is a Python object. Next, we open a file (note that we open to write bytes in Python 3+), then we use pickle. dump() to put the dict into opened file, then close. Use pickle.

What is pickling in Python example?

Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script. # Python3 program to illustrate store. # efficiently using pickle module.

What is pickling method 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.

Why is it called pickling in Python?

"Pickling" is process which enables storage and preservation. "Pickle" is "Pickle" because "Python" is "Python".


Video Answer


1 Answers

You can use functools.partial for this:

from functools import partial

def __reduce__():
     return (partial(<A callable object>, <kwargs>), ())
like image 187
amin_nejad Avatar answered Oct 17 '22 08:10

amin_nejad