Best way to pickle functions

Aaron Brady castironpi at gmail.com
Fri Apr 3 18:57:42 CEST 2009


On Apr 3, 11:04 am, Aaron Scott <aaron.hildebra... at gmail.com> wrote:
> I have a number of functions that I need to pickle without necessarily
> knowing their names in advance. My first thought was to put all the
> functions in a class, then pickle the class, but it doesn't really
> work like I expected it to.
>
>         import cPickle
>         class PickleClass:
>                 def Awesome(self):
>                         pass
>         stored = cPickle.dumps(PickleClass)
snip
> So, the class itself isn't being pickled, just an instance of it.
>
> This being the case, what's the best way to store these functions?
> Maybe dump the class to a string and pull them back with an exec
> statement when I need them?

All pickling a class does is pickle its module and name.  You can't
pickle functions in principle because byte-code is sensitive and
volatile, and is least likely to run consistently later on.  'pickle'
is not just for serialization, it's for persistence.

Pickling the source code is much sturdier.  It's very unlikely that
the same code runs differently in different interpreters.  It's much
more likely that the same code runs the same, or not at all.

It's better yet to just get the source from the original place every
time: instead, pickle a file name and open the file.



More information about the Python-list mailing list