Pickle vs XML for file I/O

C

crystalattice

I'm creating an RPG for experience and practice. I've finished a
character creation module and I'm trying to figure out how to get the
file I/O to work.

I've read through the python newsgroup and it appears that shelve
probably isn't the best option for various reasons. This lead me to
try messing w/ pickle, but I can't figure out how to use it with
classes. I've found many examples of using pickle w/ non-OOP code but
nothing that shows how to use it w/ classes, subclasses, etc. I've
read the documentation but it doesn't explain it well enough for me.

Then I started thinking perhaps I'm going about it wrong. My current
thought is to save an instance of each character so all the info (name,
skills, hit points, etc.) is stored in one place. But looking at
OpenRPG made me think that perhaps using XML to store the information
would be better. Each character could have a separate XML file, though
I don't know how it would work if many NPC's are required.

I guess my question is, what are the benifits of getting pickle to work
w/ my classes vs. converting all the character data into XML and just
writing that to a file? Since most of the data would need to be
modified often, e.g. hit points, is one storage format better than the
other? Can you even modify data if it's been pickled w/o having to
unpickle it, change the data, then repickle it?
 
S

Simon Forman

crystalattice said:
I'm creating an RPG for experience and practice. I've finished a
character creation module and I'm trying to figure out how to get the
file I/O to work.

I've read through the python newsgroup and it appears that shelve
probably isn't the best option for various reasons. This lead me to
try messing w/ pickle, but I can't figure out how to use it with
classes. I've found many examples of using pickle w/ non-OOP code but
nothing that shows how to use it w/ classes, subclasses, etc. I've
read the documentation but it doesn't explain it well enough for me.

Then I started thinking perhaps I'm going about it wrong. My current
thought is to save an instance of each character so all the info (name,
skills, hit points, etc.) is stored in one place. But looking at
OpenRPG made me think that perhaps using XML to store the information
would be better. Each character could have a separate XML file, though
I don't know how it would work if many NPC's are required.

I guess my question is, what are the benifits of getting pickle to work
w/ my classes vs. converting all the character data into XML and just
writing that to a file? Since most of the data would need to be
modified often, e.g. hit points, is one storage format better than the
other? Can you even modify data if it's been pickled w/o having to
unpickle it, change the data, then repickle it?

Um, there's nothing tricky to using pickle with classes:

|>> import pickle
|>> class foo: pass
|>> f = foo()
|>> pstr = pickle.dumps(f)
|>> pstr
'(i__main__\nfoo\np0\n(dp1\nb.'
|>> newf = pickle.loads(pstr)
|>> newf
<__main__.foo instance at 0xb664690c>

Pickle is simple and should work "out-of-the-box". I wouldn't mess
with XML until I was sure I needed it for something.

What kind of trouble were you having with pickle?

Peace,
~Simon
 
C

crystalattice

Um, there's nothing tricky to using pickle with classes:

|>> import pickle
|>> class foo: pass
|>> f = foo()
|>> pstr = pickle.dumps(f)
|>> pstr
'(i__main__\nfoo\np0\n(dp1\nb.'
|>> newf = pickle.loads(pstr)
|>> newf
<__main__.foo instance at 0xb664690c>

Pickle is simple and should work "out-of-the-box". I wouldn't mess
with XML until I was sure I needed it for something.

What kind of trouble were you having with pickle?

Peace,
~Simon
It's mostly a combination of things (I hope you can follow my logic).
First, to use "good programming practice", I want to implement a
try/except block for opening the pickle file. But I can't figure out if
this block should be included outside the classes, included in just the
base class, or if the base and subclasses need it; I'm leaning to putting
outside the classes as a global method.

When pickling a class instance, is the pickle statement placed within the
class (say, at the end of the class) or is it where the instance is
created, such as a test() method?

Do I even need to bother with having the try/except block and pickle
statements in the character generation module or should I have a separate
module that does the file I/O, such that it opens the new file, calls the
character module and makes a new instance, then pickles it?

Plus, to modify data in a class, do I have to unpickle the whole thing
first or is there a way to modify the data while it's pickled? Actually,
I think I can answer that last question: a character instance, having
been created, will stay resident in memory until the player quits,
character dies, or otherwise is no longer needed. At that point the
character instance should be pickled (if necessary) to disk; pickle
shouldn't be used while data modification is required and the class
instance is "active", correct?

I also remember reading on a thread here that pickle sometimes has issues
when used with classes, which makes me hesitant to pickle an entire class
instance. That's why I thought XML may be safer/better.
 
J

John Machin

crystalattice said:
Plus, to modify data in a class

I presume the word "instance" is missing here ...
do I have to unpickle the whole thing
first or is there a way to modify the data while it's pickled? Actually,
I think I can answer that last question: a character instance, having
been created, will stay resident in memory until the player quits,
character dies, or otherwise is no longer needed. At that point the
character instance should be pickled (if necessary) to disk; pickle
shouldn't be used while data modification is required and the class
instance is "active", correct?

A pickle is a snapshot of an object and its contents. If the real
scenery changes, you need to take another photo.

Unpickling creates another instance from the blueprint. You can repeat
this to obtain multiple distinct copies of the instance.

Partial unpickling is not possible.

Use cPickle if you can; it's much faster.

HTH,
John
 
M

Marc 'BlackJack' Rintsch

It's mostly a combination of things (I hope you can follow my logic).
First, to use "good programming practice", I want to implement a
try/except block for opening the pickle file. But I can't figure out if
this block should be included outside the classes, included in just the
base class, or if the base and subclasses need it; I'm leaning to putting
outside the classes as a global method.

That's not a problem with pickle but where you think a potential IO error
is handled best. Ask yourself if you can do something sensible at the
point where you catch an exception. If you don't know what to do with it,
don't catch it and just let it propagate.
When pickling a class instance, is the pickle statement placed within the
class (say, at the end of the class) or is it where the instance is
created, such as a test() method?

`pickle.dump()` and `pickle.load()` are not statements but just functions.
And you should place a call where you actually want to save or load
instances in your program flow.
Plus, to modify data in a class, do I have to unpickle the whole thing
first or is there a way to modify the data while it's pickled? Actually,
I think I can answer that last question: a character instance, having
been created, will stay resident in memory until the player quits,
character dies, or otherwise is no longer needed. At that point the
character instance should be pickled (if necessary) to disk; pickle
shouldn't be used while data modification is required and the class
instance is "active", correct?

Yes that's correct. It wouldn't be different with XML.
I also remember reading on a thread here that pickle sometimes has issues
when used with classes, which makes me hesitant to pickle an entire class
instance. That's why I thought XML may be safer/better.

You can't pickle everything. Files for example are unpickleable and you
can't pickle code so pickling classes is not that useful.

An advantage of `pickle` is that it's in the standard library and ready to
use for serialization. To get an XML solution you must either write your
own serialization code or use a 3rd party library.

What are the problems you fear when using `shelve` by the way?

Ciao,
Marc 'BlackJack' Rintsch
 
S

Simon Hibbs

I've recently gone through a similar evaluation of my options for
persisting data. Object serialization to pickles or XML is a very easy,
quick way of persisting data but it does have drawbacks. I'm not a
professional developer, so if there are errors in my analysis, I'd love
to be corrected.

Suppose you make some changes to the object format - adding some new
attributes or properties. Suddenly your existing test data is useless.
At least with XML you can edit the files by hand to add dummy data, but
with pickles that's not an option and even with XML it's a painful and
error prone process.

Idealy you need to be able to browse and edit your saved data outside
the main program, to scan for errors, fix them manualy and easily
update your data structure as the application data model grows and
changes.

There are good reasons why relational databases are the default data
store for many professional applications because you can parse and edit
the data very easily using external tools. Personaly I'd go with
SQLite. It's soon to be a part of the Python standard library with 2.5
and is very compact. It can be a lot more work than just serializing
automaticaly, but there are toolkits such as SQLObject and SQL Alchemy
that can automate this as well.

Best regards,

Simon Hibbs
 
C

crystalattice

Marc said:
That's not a problem with pickle but where you think a potential IO error
is handled best. Ask yourself if you can do something sensible at the
point where you catch an exception. If you don't know what to do with it,
don't catch it and just let it propagate.


`pickle.dump()` and `pickle.load()` are not statements but just functions.
And you should place a call where you actually want to save or load
instances in your program flow.


Yes that's correct. It wouldn't be different with XML.


You can't pickle everything. Files for example are unpickleable and you
can't pickle code so pickling classes is not that useful.

An advantage of `pickle` is that it's in the standard library and ready to
use for serialization. To get an XML solution you must either write your
own serialization code or use a 3rd party library.

What are the problems you fear when using `shelve` by the way?

Ciao,
Marc 'BlackJack' Rintsch
The ideas I got about shelve are mostly due to this thread:
http://tinyurl.com/lueok. There weren't any other threads
contradicting the information so I figured it has merit. Actually, not
many people seem to use shelve very much; pickle is used more often so
I decided to give it a try and see how it works for me.
 
C

crystalattice

Simon said:
I've recently gone through a similar evaluation of my options for
persisting data. Object serialization to pickles or XML is a very easy,
quick way of persisting data but it does have drawbacks. I'm not a
professional developer, so if there are errors in my analysis, I'd love
to be corrected.

Suppose you make some changes to the object format - adding some new
attributes or properties. Suddenly your existing test data is useless.
At least with XML you can edit the files by hand to add dummy data, but
with pickles that's not an option and even with XML it's a painful and
error prone process.

Idealy you need to be able to browse and edit your saved data outside
the main program, to scan for errors, fix them manualy and easily
update your data structure as the application data model grows and
changes.

There are good reasons why relational databases are the default data
store for many professional applications because you can parse and edit
the data very easily using external tools. Personaly I'd go with
SQLite. It's soon to be a part of the Python standard library with 2.5
and is very compact. It can be a lot more work than just serializing
automaticaly, but there are toolkits such as SQLObject and SQL Alchemy
that can automate this as well.

Best regards,

Simon Hibbs
That's a good idea. I may implement that later. Right now though I'm
mostly doing this as a hobby and an open-source project, so I don't
want to add too much extra to the project. I want to see what the base
Python language is capable of before I start using other toolkits and
libraries. I just barely got comfortable with the OOP "mindset" so
even working w/ classes and objects is still a struggle sometimes.
 
M

Marc 'BlackJack' Rintsch

crystalattice said:
The ideas I got about shelve are mostly due to this thread:
http://tinyurl.com/lueok. There weren't any other threads
contradicting the information so I figured it has merit.

Main complaint seemed to be that data might be corrupted when the program
terminates "abnormal" while writing the data. You have the very same
problem with pickle or XML serialization. If the program gets interrupted
after only half the data is written to disk you lose information.
Actually, not many people seem to use shelve very much; pickle is used
more often so I decided to give it a try and see how it works for me.

They have a slightly different use case. `pickle` stores single objects
and `shelve` is a sort of persistent dictionary that maps strings to
objects. So if you want to save a party of characters and load them back
together than pickle a list with those characters. If you want a database
of many characters the player can choose from than you might want to store
them in a `shelve`.

Ciao,
Marc 'BlackJack' Rintsch
 
C

crystalattice

Marc said:
Main complaint seemed to be that data might be corrupted when the program
terminates "abnormal" while writing the data. You have the very same
problem with pickle or XML serialization. If the program gets interrupted
after only half the data is written to disk you lose information.


They have a slightly different use case. `pickle` stores single objects
and `shelve` is a sort of persistent dictionary that maps strings to
objects. So if you want to save a party of characters and load them back
together than pickle a list with those characters. If you want a database
of many characters the player can choose from than you might want to store
them in a `shelve`.

Ciao,
Marc 'BlackJack' Rintsch

Okay, that makes sense. I was able to figure out how to pickle
yesterday. It's not as hard as I thought (obviously); my confusion
originally came from thinking I needed to pickle each item of the class
separately but I realized that pickling a class instance worked too.

One other question though (hope it doesn't sound silly/stupid). Your
suggestion to "pickle a party" using a list has me thinking: can a
list store class instances? I imagine it can though I don't know if
there may be bad juju if I tried, like data corruption or errors or
something. I've only been using classes for a few weeks so I don't
know very much about them.

For example, if I wanted to store a party of characters, rather than
pickling each person separately could I put each character instance in
a list then pickle the list? Like this:

char1 = Character()
char2 = Character()
char3 = Character()
party = [char1, char2, char3]
file = open("partyfile.dat", "w")
pickle.dump(party, file)
 
M

Marc 'BlackJack' Rintsch

crystalattice said:
One other question though (hope it doesn't sound silly/stupid). Your
suggestion to "pickle a party" using a list has me thinking: can a
list store class instances?

Yes of course you can store class instances in lists.
For example, if I wanted to store a party of characters, rather than
pickling each person separately could I put each character instance in
a list then pickle the list? Like this:

char1 = Character()
char2 = Character()
char3 = Character()
party = [char1, char2, char3]
file = open("partyfile.dat", "w")
pickle.dump(party, file)

Yes that would work.

Ciao,
Marc 'BlackJack' Rintsch
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top