Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pickle an instance of a class which is written inside a function?

Tags:

python

pickle

Suppose I have this snippet inside a module

def func(params):
   class MyClass(object):
       pass

How can I pickle an instance of the class MyClass ?

like image 237
Plaban Nayak Avatar asked Oct 08 '22 00:10

Plaban Nayak


1 Answers

You can't, because picklable object's class definitions must reside in an imported module's scope. Just put your class inside module scope and you are good to go.

That said, in Python there is very little that can't be achieved with a bit of hacking the insides of the machinery (sys.modules in this case), but I wouldn't recommend that.

like image 116
XORcist Avatar answered Oct 13 '22 10:10

XORcist