How can I pickle a python object which contains lambdas?
Can't pickle local object 'BaseDiscretizer.__init__.<locals>.<lambda>'
is the error I get when trying to pickle https://github.com/marcotcr/lime/blob/97a1e2d7c1adf7b0c4f0d3b3e9b15f6197b75c5d/lime/discretize.py when pickling the https://github.com/marcotcr/lime/blob/2703bcdcddd135947fe74e99cc270aa4fac3263a/lime/lime_tabular.py#L88 LimeTabularExplainer
Yes, python can pickle lambda functions… but only if you have something that uses copy_reg to register how to pickle lambda functions -- the package dill loads the copy_reg you need into the pickle registry for you, when you import dill .
Classes, functions, and methods cannot be pickled -- if you pickle an object, the object's class is not pickled, just a string that identifies what class it belongs to.
Pros of lambda functions:Lambda functions are inline functions and thus execute comparatively faster. Many times lambda functions make code much more readable by avoiding the logical jumps caused by function calls.
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument.
The standard pickle
module cannot serialize lambdas, but there is a third party package called dill
which supports them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With