Help with saving and restoring program state

M.E.Farmer mefjr75 at
Tue Jan 25 18:16:32 EST 2005

Jacob H wrote:
> Hello list...
> I'm developing an adventure game in Python (which of course is lots
> fun).

I am glad you are having fun ,
after all life is so short,
isn't that what it is all about ;)

> One of the features is the ability to save games and restore the
> saves later. I'm using the pickle module to implement this. Capturing
> current program state and neatly replacing it later is proving to be
> trickier than I first imagined, so I'm here to ask for a little
> direction from wiser minds than mine!
> When my program initializes, each game object is stored in two places
> -- the defining module, and in a list in another module. The
> example is not from my actual code, but what happens is the same.
> (code contained in "globalstate" module)
> all_fruit = []
> (code contained in "world" module)
> class Apple(object): # the class hierarchy goes back to object,
>     def __init__(self):
> = 23
> = "something"
>     	globalstate.all_fruit.append(self)
> apple = Apple()
Ok here is a guess. (I recently did something similar, maybe this will
If you already knew about this stuff then just ignore me :)

You have defined a class for your objects, which is a nifty
The apple class can also keep track of the total amount of apple
instances handed out.
Sometimes it is better to let the objects handle there own state.
Py> class Apple(object):
...     total = 0 # this is a 'class variable' shared by all instances

...     def __init__(self):
...    += 1
... = 23 # this is an 'instance variable/name'
... = "something"
... apple = Apple()
... apple_two = Apple()
... print
... 2
... apple_three = Apple()
... print
... 3
... print
... 3
Now you can just pickle them and when you unpickle them as usual.

Also another idea is to use a class instead of a global.
I'll admit it I have a personal distaste for them, but classes work so
well I never miss them.

Py>class Store(object):
...    pass

Now just create an instance and add your attributes.
Py>store = Store() = 'red' = 5.7 = 42
And get them back when needed.


More information about the Python-list mailing list