tags:

views:

68

answers:

2

Is there a way to pickle a class definition?

What I'd like to do is pickle the definition (which may created dynamically), and then send it over a TCP connection so that an instance can be created on the other end.

I understand that there may be dependencies, like modules and global variables that the class relies on. I'd like to bundle these in the pickling process as well, but I'm not concerned about automatically detecting the dependencies because it's okay if the onus is on the user to specify them.

+1  A: 

Alas, not directly. You can send the string form of the class statement, or a bytecode form, and "rehydrate" it with an exec on the receiving end.

Alex Martelli
Are you referring to just sending the .py or .pyc files containing the class statement?
Giorgio
@Giorgio, you don't necessarily need to send _all_ of the `.py` or `.pyc` file, just the source of the class itself (as identified by http://docs.python.org/library/inspect.html?#inspect.getsource) or its `compile`d form.
Alex Martelli
+1  A: 

The documentation does a pretty good job of explaining what can and can't be pickled, and why that is.

http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled

Basically, if the class or module is importable by name when it gets unpickled, it should work, unless you plan on changing your class definition between now and when you unpickle it. In the class definition below, only the class name "Test", and the method name "mymethod" will be pickled. If you pickle out the class definition, then change the definition so that attr is a different value, and mymethod does something completely different, the pickle will pick up the new definition.

class Test(object):
    attr = 5

    def mymethod(self, arg):
        return arg
Brendan Abel