pickling class instances with __slots__

Discussion in 'Python' started by Alex, Oct 29, 2005.

  1. Alex

    Alex Guest

    I would greatly appreciate an advice on the following matter that was
    very much discussed circa 2002 but in all this discussion I could not
    find the final answer with a code example. Neither I can find it in
    Python documentation.


    I have a series of new classes with child-parent relationship and each
    has unique __slots__. They don't have __dict__ . I need to be able to
    pickle and unpickle them. As far as I could understand, I need to
    provide __getstate__ and __setstate__ methods for each class. Is
    there a universally accepted code for each method? If so, what is it?
    If there is no standard, what works?


    TIA


    Alex
     
    Alex, Oct 29, 2005
    #1
    1. Advertising

  2. Alex <> wrote:
    ...
    > I have a series of new classes with child-parent relationship and each
    > has unique __slots__. They don't have __dict__ . I need to be able to
    > pickle and unpickle them. As far as I could understand, I need to
    > provide __getstate__ and __setstate__ methods for each class. Is


    Right.

    > there a universally accepted code for each method? If so, what is it?
    > If there is no standard, what works?


    Lots of things work, the simplest is something like:

    >>> class wehaveslots(object):

    .... __slots__ = 'a', 'b', 'c'
    .... def __getstate__(self): return self.a, self.b, self.c
    .... def __setstate__(self, tup): self.a, self.b, self.c = tup

    (plus presumably other methods, but those don't matter for pickle).


    Alex
     
    Alex Martelli, Oct 29, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Wohlbier
    Replies:
    2
    Views:
    399
    Josiah Carlson
    Feb 22, 2004
  2. Erik Max Francis
    Replies:
    1
    Views:
    407
    Erik Max Francis
    Aug 9, 2005
  3. Ewald R. de Wit

    __slots__ and class attributes

    Ewald R. de Wit, Nov 3, 2005, in forum: Python
    Replies:
    2
    Views:
    311
    Ewald R. de Wit
    Nov 4, 2005
  4. Nicolas M. Thiéry

    Pickling classes (not class instances)

    Nicolas M. Thiéry, Jan 10, 2009, in forum: Python
    Replies:
    2
    Views:
    368
    Aaron Brady
    Feb 14, 2009
  5. lars van gemerden
    Replies:
    10
    Views:
    668
    lars van gemerden
    Jan 3, 2012
Loading...

Share This Page