Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Pickle a Class (http://www.programmingforums.org/showthread.php?t=11834)

Dietrich Nov 8th, 2006 6:33 PM

Pickle a Class
 
Does anybody have a good example of using a pickle dump and load on a class?

DaWei Nov 8th, 2006 7:01 PM

I used it to store the patterns tree for the TicTacToe game:
:

def makeSet ():
    '''
    Derive a set of Basic Patterns
    '''
    tree = [[Pattern ()]]
    count = 1
    for level in range (1, 10):
        ordinal = 0
        sym = (level % 2)
        if sym == 0: sym = 2
        tree.append ([])
        for i in range (len (tree [level-1])):
            # Each pattern in the previous set
            # Don't follow up on game end
            if tree [level-1][i].winner or tree [level-1][i].draw: continue
            for j in range (9):
                # Each possible square
                testpattern = tree [level-1][i].pattern [:]
                if testpattern [j] == 0: testpattern [j] = sym
                else: continue
                transform = ""

                for k in range (len (tree [level])):
                    # Each existing sibling
                    transform = equiv (testpattern, tree [level][k].pattern)
                    if transform != "": break

                if transform == "":
                    # New basic pattern
                    tree [level].append (Pattern (level, ordinal, [], []))
                    tree [level][ordinal].pattern = testpattern
                    tree [level][ordinal].parent = []
                    tree [level][ordinal].children = []
                    tree [level][ordinal].winner = checkWin (tree [level][ordinal])
                    tree [level][ordinal].draw = checkDraw (tree [level][ordinal])
                    tree [level-1][i].children.append ([ordinal, transform])
                    ordinal += 1
                else:
                    # Equivalent child exists with another parent
                    if tree [level-1][i].children.count (tree [level][k].ordinal) == 0:
                        # Record it with this parent, if not already present
                        tree [level-1][i].children.append ([tree [level][k].ordinal, transform])
    file = open ("patterns.dat", "wb")
    pickle.dump (tree, file)
    file.close ()
    return tree

...and to retrieve it:
:

...
file = open ("patterns.dat", "rb")
tree = pickle.load (file)
file.close ()
...

The class:
:

class Pattern:

    def __init__(self, level = 0, ordinal = 0, parent = [],
                children = [], pattern = [0,0,0,0,0,0,0,0,0]):
        self.level = level
        self.ordinal = ordinal
        self.parent = parent
        self.children = children
        self.pattern = pattern
        self.wins = 0
        self.draws = 0
        self.losses = 0
        self.winner = 0
        self.draw = False


Dietrich Nov 10th, 2006 1:37 AM

Interesting! You pickle dumped and loaded a list of class instances.

Dietrich Nov 14th, 2006 12:13 PM

Can you pickle a class directly rather than its instance?

DaWei Nov 14th, 2006 12:45 PM

Haven't tried it; should take you a couple minutes to find out. Why would you want to pickle a class definition?

Arevos Nov 14th, 2006 2:36 PM

Quote:

Originally Posted by Dietrich (Post 118910)
Can you pickle a class directly rather than its instance?

No, at least not directly. There may be a way to do it indirectly, perhaps... Though, as DaWei says, why would you want to pickle a class in the first place?

Dietrich Nov 16th, 2006 6:39 PM

I thought that if you pickle the instance of a class and load it into another program you have to supply the class.

Somewhere I found this note:
"use class methods __getstate__ and __setstate__ to pickle a class"

Pickle allows one to pickle any object, right?

DaWei Nov 16th, 2006 6:42 PM

I'm still not saying you can't do it (I haven't checked), but you have to ask yourself if a class definition is an object. A blueprint is not a house or a lawnmower.

Arevos Nov 17th, 2006 2:43 AM

Well, in Python a class definition is an object. But class objects tend to have complications associated with them. Pickling a normal object instance is just a matter of looking at its __dict__ and then turning all its variables into strings. Pickling a class would involve including Python bytecode as well, which is somewhat harder.

Setting __getstate__ and __setstate__ on an object overrides Pickle's default serialization and deserialization routines, allowing you to define manually how your object is turned into a string. Other than that, you could play around with the code and code.compile modules, but they tend to be rather sparse on documentation.

Is there a reason you really need to pickle a class? Could it not conceivably be done another way?

Dietrich Nov 17th, 2006 1:38 PM

Thanks Arevos, I think the easier way would be to import the class as a module.


All times are GMT -5. The time now is 8:14 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC