pickling and methods

Steve Holden sholden at holdenweb.com
Thu Jul 5 00:54:54 EDT 2001


"gods1child" <alankarmisra at hotmail.com> wrote in message
news:25b2e0d9.0107041354.161f2cd3 at posting.google.com...
> Hi,
>
> When an object instance is pickled, is the byte-code associated with
> the object's methods stored with it? Or does Python pickle only the
> object type and state information ? for example if i have:
> class Class:
>     def function():
>        self.stateinfo = 'mystate'
>        pass # large amount of code here
>
> a = Class()
> b = Class()
>
> If i pickled a and b, would they both have the byte-code for the
> method 'function' or would they only have the class (Class) and the
> state information (stateinfo)?
>
> The reason for asking this is because I have a class which has a large
> amount of code in its __init__ method. Once the object is created,
> most of that code is pretty much useless. Many instances of this
> object will be pickled during program execution. If Python does store
> the function byte code with each instance of the object, I wanted to
> consider the space saving i might achieve by moving most of the
> processing code to a object-factory class instead which would return a
> light weight class which i can pickle.
>
> Even from a good programming perspective, i wanted to know your
> opinions of moving the __init__ code to a factory method in cases
> where the processing code is huge and is never used (not even while
> unpickling) once the object is instantiated.
>
When you unpickle an instance, it imports the class from the original module
in which it was defined. This is why you can't successfully pickle instances
of objects whose class is in the __main__ module: Python doesn't know where
to go to get their definitions.

You can therefore assume it keeps only the state information in the pickle.
Of course, if that includes references to other objects your pickle can
anyway end up larger than you think.

regards
 Steve

--
http://www.holdenweb.com/








More information about the Python-list mailing list