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

Home Posts Topics Members FAQ

Pickle Problem

I'm a complete python n00b writing my first program (or attempting to,
anyway). I'm trying to make the transition from Java, so if you could
help me, it would be greatly appreciated. Here's the code I'm stuck on
(It's very basic):

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(sel f, path = "test.txt") :
fw = file(path, "w")
pickle.dump(sel f.title, fw)
fw.close()

if __name__=='__ma in__':
x = DemoClass
x.WriteToFile

It doesn't do any file I/O at all (that I see). I hope my syntax is
alright. If I just call WriteToFile, shouldn't it perform with the
default path? It gives me no errors and pretends to execute just fine.

Mar 15 '07 #1
9 1323
On Mar 15, 11:13 am, "tonyr1988" <tonyr1...@gmai l.comwrote:
if __name__=='__ma in__':
x = DemoClass
x.WriteToFile
You meant to create a DemoClass instance object, but instead, you
obtained a reference to the class object. You want 'x = DemoClass()'
instead.
You meant to call the WriteToFile method, but instead, you obtained a
reference to the method object. You want 'x.WriteToFile( )' instead.

Mar 15 '07 #2
In <11************ **********@d57g 2000hsg.googleg roups.com>, tonyr1988
wrote:
if __name__=='__ma in__':
x = DemoClass
x.WriteToFile
In Python classes, functions and methods are first class objects. You
bind the `DemoClass` class object to the name `x`, you are *not* creating
an instance of `DemoClass`.

Then you access the attribute `WriteToFile` of the `DemoClass` class
object. But you don't do anything with it.

In [39]: class DemoClass(objec t): pass
....:

In [40]: x = DemoClass

In [41]: x
Out[41]: <class '__main__.DemoC lass'>

In [42]: y = DemoClass()

In [43]: y
Out[43]: <__main__.DemoC lass object at 0xb5a3fd4c>

In [44]: x()
Out[44]: <__main__.DemoC lass object at 0xb5a3fc2c>

You have to call the class object and the method to see any effects.

Ciao,
Marc 'BlackJack' Rintsch
Mar 15 '07 #3
tonyr1988 wrote:
I'm a complete python n00b writing my first program (or attempting to,
anyway). I'm trying to make the transition from Java, so if you could
help me, it would be greatly appreciated. Here's the code I'm stuck on
(It's very basic):

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(sel f, path = "test.txt") :
fw = file(path, "w")
pickle.dump(sel f.title, fw)
fw.close()

if __name__=='__ma in__':
x = DemoClass
x.WriteToFile

It doesn't do any file I/O at all (that I see). I hope my syntax is
alright. If I just call WriteToFile, shouldn't it perform with the
default path? It gives me no errors and pretends to execute just fine.
Just a couple of "issues" that can be fixed as follows:

import pickle

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(sel f, path):
fw = file(path, "w")
pickle.dump(sel f.title, fw)
fw.close()

if __name__=='__ma in__':
path='\\test.tx t'
x = DemoClass()
x.WriteToFile(p ath)

Notes:

1) You have to call (follow by parenthesis) DemoClass() to get an instance.
What you got was a pointer (x) to the DemoClass not an instance of
DemoClass.

2) Same for WriteToFile()

3) Probably best to move the path to main and always pass it into
WriteToFile.

-Larry
Mar 15 '07 #4
On 15 Mar 2007 08:13:53 -0700, tonyr1988 <to*******@gmai l.comwrote:
if __name__=='__ma in__':
x = DemoClass
x.WriteToFile
Here, you're binding the Class DemoClass to the name x. What you
probably meant to do is create a new instance of DemoClass, and bind
that to name x, like this:

if __name__=='__ma in__':
x = DemoClass()
x.WriteToFile

When I make that change, your code appears to work fine.

--
Jerry
Mar 15 '07 #5
tonyr1988 wrote:
I'm a complete python n00b writing my first program (or attempting to,
anyway). I'm trying to make the transition from Java, so if you could
help me, it would be greatly appreciated. Here's the code I'm stuck on
(It's very basic):

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(sel f, path = "test.txt") :
fw = file(path, "w")
pickle.dump(sel f.title, fw)
fw.close()

if __name__=='__ma in__':
x = DemoClass
x.WriteToFile

It doesn't do any file I/O at all (that I see). I hope my syntax is
alright. If I just call WriteToFile, shouldn't it perform with the
default path? It gives me no errors and pretends to execute just fine.
Several people have pointed out the problem, but when you get that
fixed, I see another bit of trouble. The pickle format is a binary
format (be default), but you don't open the file in binary mode. On
Unix the distinction is (wisely) irrelevant, but on Windows you should
open the file with a mode of "wb" not just "w".

Mar 15 '07 #6
Hi,

You should write your last two lines as ...

x = DemoClass()
x.WriteToFile()

Don't miss paranthesis again... :)

Maybe there are still some mistakes too. Does dump method writes list's
elements?

Sönmez

tonyr1988 wrote:
I'm a complete python n00b writing my first program (or attempting to,
anyway). I'm trying to make the transition from Java, so if you could
help me, it would be greatly appreciated. Here's the code I'm stuck on
(It's very basic):

class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]

def WriteToFile(sel f, path = "test.txt") :
fw = file(path, "w")
pickle.dump(sel f.title, fw)
fw.close()

if __name__=='__ma in__':
x = DemoClass
x.WriteToFile

It doesn't do any file I/O at all (that I see). I hope my syntax is
alright. If I just call WriteToFile, shouldn't it perform with the
default path? It gives me no errors and pretends to execute just fine.
Mar 15 '07 #7
On Mar 15, 10:38 am, Gary Herron <gher...@island training.comwro te:
tonyr1988 wrote:
I'm a complete python n00b writing my first program (or attempting to,
anyway). I'm trying to make the transition from Java, so if you could
help me, it would be greatly appreciated. Here's the code I'm stuck on
(It's very basic):
class DemoClass:
def __init__(self):
self.title = ["Hello", "Goodbye"]
def WriteToFile(sel f, path = "test.txt") :
fw = file(path, "w")
pickle.dump(sel f.title, fw)
fw.close()
if __name__=='__ma in__':
x = DemoClass
x.WriteToFile
It doesn't do any file I/O at all (that I see). I hope my syntax is
alright. If I just call WriteToFile, shouldn't it perform with the
default path? It gives me no errors and pretends to execute just fine.

Several people have pointed out the problem, but when you get that
fixed, I see another bit of trouble. The pickle format is a binary
format (be default), but you don't open the file in binary mode. On
Unix the distinction is (wisely) irrelevant, but on Windows you should
open the file with a mode of "wb" not just "w".
Thanks guys for all the help. Sure enough, it was the parenthesis.
Most of my problems seem to be from under-simplifying (using
semicolons, brackets, etc) or, rarely, over-simplifying (forgetting
parenthesis). The biggest thing that was messing me up was the
mandatory "self" input. For some reason I was thinking that, if I had
parenthesis, I would have to define it. Fixing that works perfectly.

Also, about the binary format for opening files. The program that I'm
working on now is completely Linux-based - it's impossible for it to
work on any other OS. Should I still open with "wb" or not? Either
way, thanks for that tip!

One more (completely irrelevant) question. I don't quite understand
the double-underscore functions / methods / etc, such as __name__,
__main__, __init__. Is there a reason for the double-underscore? Does
it make anything special?

Again, thanks for the help...I'm probably going to ask a lot more of
it before too long. :)

Mar 15 '07 #8
Gary Herron <gh*****@island training.comwro te:
...
fixed, I see another bit of trouble. The pickle format is a binary
format (be default), but you don't open the file in binary mode. On
Alas, wish it were:-(.

Unfortunately, snipping the right snippet from help(pickle) ...:

"""
| The optional protocol argument tells the pickler to use the
| given protocol; supported protocols are 0, 1, 2. The
default
| protocol is 0, to be backwards compatible. (Protocol 0 is
the
| only protocol that can be written to a file opened in text
| mode and read back successfully. When using a protocol
higher
| than 0, make sure the file is opened in binary mode, both
when
| pickling and unpickling.)
|
| Protocol 1 is more efficient than protocol 0; protocol 2 is
| more efficient than protocol 1.
"""

So, by default, you're using the most inefficient protocol... but, you
can write it out to a file opened in text mode and read it back.
Alex
Mar 16 '07 #9
I'm trying to make the transition from Java
The biggest thing that was messing me up was the
mandatory "self" input. For some reason I was thinking
that, if I had parenthesis, I would have to define it.
I think things are pretty similar in Java. Java does the same thing
except 'self' is invisible in Java, and in Java 'self' is called
'this'. For instance, in Java you can write:

int num;

void setNum(int num)
{
this->num = num
}

Where did 'this' come from? In Java, methods are passed the invisible
'this' argument, which you can then access inside the method. It
looks like Python just "uncloaks" Java's 'this'.
Mar 16 '07 #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...
10
4452
by: crystalattice | last post by:
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...
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...
2
6567
by: Victor Lin | last post by:
Hi, I encounter a problem with pickle. I download a html from: http://www.amazon.com/Magellan-Maestro-4040-Widescreen-Navigator/dp/B000NMKHW6/ref=sr_1_2?ie=UTF8&s=electronics&qid=1202541889&sr=1-2 and parse it with BeautifulSoup. This page is very huge. When I use pickle to dump it, a RuntimeError: maximum recursion depth
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
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...
1
10541
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...
1
7753
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
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();...
0
5789
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
3972
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3078
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.