473,656 Members | 2,793 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 1313
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
5113
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
4009
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
1776
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
4435
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
93026
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
6561
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
6088
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
4502
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
1742
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
6341
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
8382
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
8816
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
8498
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
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
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
5629
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
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
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
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.