473,832 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Pickle vs XML for file I/O

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?

Aug 1 '06 #1
10 4451
crystalattice wrote:
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__\nfo o\np0\n(dp1\nb. '
|>newf = pickle.loads(ps tr)
|>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

Aug 1 '06 #2
On Mon, 31 Jul 2006 14:35:39 -1000, Simon Forman <ro*********@ya hoo.com>
wrote:
crystalattice wrote:
>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__\nfo o\np0\n(dp1\nb. '
|>newf = pickle.loads(ps tr)
|>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.
--
Python-based online RPG in development based on the Colonial Marines from
"Aliens": http://cmrpg.sourceforge.net

Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Aug 1 '06 #3

crystalattice wrote:
>
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

Aug 1 '06 #4
In <op************ ***@emac.local> , crystalattice wrote:
On Mon, 31 Jul 2006 14:35:39 -1000, Simon Forman <ro*********@ya hoo.com>
wrote:
>What kind of trouble were you having with pickle?

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

Aug 1 '06 #5

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

Aug 1 '06 #6

Marc 'BlackJack' Rintsch wrote:
In <op************ ***@emac.local> , crystalattice wrote:
On Mon, 31 Jul 2006 14:35:39 -1000, Simon Forman <ro*********@ya hoo.com>
wrote:
What kind of trouble were you having with pickle?
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
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.

Aug 1 '06 #7
Simon Hibbs wrote:
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.

Aug 1 '06 #8
In <11************ **********@m79g 2000cwm.googleg roups.com>, crystalattice
wrote:
>What are the problems you fear when using `shelve` by the way?
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
Aug 2 '06 #9
Marc 'BlackJack' Rintsch wrote:
In <11************ **********@m79g 2000cwm.googleg roups.com>, crystalattice
wrote:
What are the problems you fear when using `shelve` by the way?
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
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(par ty, file)

Aug 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
5148
by: Simon Burton | last post by:
Hi, I am pickling big graphs of data and running into this problem: File "/usr/lib/python2.2/pickle.py", line 225, in save f(self, object) File "/usr/lib/python2.2/pickle.py", line 414, in save_list save(element) File "/usr/lib/python2.2/pickle.py", line 219, in save
3
4023
by: Michael Hohn | last post by:
Hi, under python 2.2, the pickle/unpickle sequence incorrectly restores a larger data structure I have. Under Python 2.3, these structures now give an explicit exception from Pickle.memoize(): assert id(obj) not in self.memo I'm shrinking the offending data structure down to find the problem
0
1789
by: Mike P. | last post by:
Hi all, I'm working on a simulation (can be considered a game) in Python where I want to be able to dump the simulation state to a file and be able to load it up later. I have used the standard Python pickle module and it works fine pickling/unpickling from files. However, I want to be able to use a third party tool like an XML editor (or other custom tool) to setup the initial state of the simulation, so I have been playing around...
6
12352
by: Jim Lewis | last post by:
Pickling an instance of a class, gives "can't pickle instancemethod objects". What does this mean? How do I find the class method creating the problem?
5
93191
by: Chris | last post by:
Why can pickle serialize references to functions, but not methods? Pickling a function serializes the function name, but pickling a staticmethod, classmethod, or instancemethod generates an error. In these cases, pickle knows the instance or class, and the method, so what's the problem? Pickle doesn't serialize code objects, so why can't it serialize the name as it does for functions? Is this one of those features that's feasible, but...
3
6111
by: fizilla | last post by:
Hello all! I have the following weird problem and since I am new to Python I somehow cannot figure out an elegant solution. The problem reduces to the following question: How to pickle a collections.defaultdict object that has set the default_factory property? For Example (from the IDLE console): >>> words = collections.defaultdict(lambda: 1) >>> f = file("temp","w")
2
3544
by: Michele Simionato | last post by:
Can somebody explain what's happening with the following script? $ echo example.py import pickle class Example(object): def __init__(self, obj, registry): self._obj = obj self._registry = registry
2
4516
by: Nagu | last post by:
I am trying to save a dictionary of size 65000X50 to a local file and I get the memory error problem. How do I go about resolving this? Is there way to partition the pickle object and combine later if this is a problem due to limited resources (memory) on the machine (it is 32 bit machine Win XP, with 4GB RAM). Here is the detail description of the error:
0
1785
by: Nagu | last post by:
I am trying to save a dictionary of size 65000X50 to a local file and I get the memory error problem. How do I go about resolving this? Is there way to partition the pickle object and combine later if this is a problem due to limited resources (memory) on the machine (it is 32 bit machine Win XP, with 4GB RAM). Please advice. Thank you,
1
6355
by: IceMan85 | last post by:
Hi to all, I have spent the whole morning trying, with no success to pickle an object that I have created. The error that I get is : Can't pickle 'SRE_Match' object: <_sre.SRE_Match object at 0x2a969c0ad0> the complete stack is the following : Traceback (most recent call last): File "manager.py", line 305, in ? commandLineExec (log, parser) File "manager.py", line 229, in commandLineExec
0
9795
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9642
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10780
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10540
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6951
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4421
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3077
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.