[Tutor] Python 3 dictionary questions

2011-11-23 Thread Cranky Frankie
In playing around with Pyton 3 dictionaries I've come up with 2 questions

1) How are duplicate keys handled? For example:

Qb_Dict = {Montana: [Joe, Montana, 415-123-4567,
joe.mont...@gmail.com,Candlestick Park],
Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
Metropolitan Stadidum],
Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High Stadium],
Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High
Stadium],
Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
Louisiana Superdome],
Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
Cowboy Stadium]}

print(Qb_Dict[Elway],\n)# print a dictionary entry

In the above the wrong Elway entry, the second one, where the first
name is Ed, is getting printed. I just added that second Elway row to
see how it would handle duplicates and the results are interesting, to
say the least.

2) Is there a way to print out the actual value of the key, like
Montana would be 0, Tarkington would be 1, etc?

-- 
Frank L. Cranky Frankie Palmeri
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3 dictionary questions

2011-11-23 Thread bob gailer

On 11/23/2011 8:04 AM, Cranky Frankie wrote:

In playing around with Pyton 3 dictionaries I've come up with 2 questions

1) How are duplicate keys handled? For example:

Qb_Dict = {Montana: [Joe, Montana, 415-123-4567,
joe.mont...@gmail.com,Candlestick Park],
Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
Metropolitan Stadidum],
Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High Stadium],
Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High
Stadium],
Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
Louisiana Superdome],
Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
Cowboy Stadium]}

print(Qb_Dict[Elway],\n)# print a dictionary entry

In the above the wrong Elway entry, the second one, where the first
name is Ed, is getting printed. I just added that second Elway row to
see how it would handle duplicates and the results are interesting, to
say the least.


Seems like you answered your first question. Dictionaries do not have 
duplicate keys. Your 2nd assignment using the key Elway replaced the 
first.


2) Is there a way to print out the actual value of the key, like
Montana would be 0, Tarkington would be 1, etc?
Actual value? The actual value of Montana is Montana. Sounds like you 
want the index of the entry as though it were in a list. Dictionaries 
are not ordered so you can't get that unless you store it as part of the 
value.


--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3 dictionary questions

2011-11-23 Thread Christian Witts

On 2011/11/23 03:04 PM, Cranky Frankie wrote:

In playing around with Pyton 3 dictionaries I've come up with 2 questions

1) How are duplicate keys handled? For example:

Qb_Dict = {Montana: [Joe, Montana, 415-123-4567,
joe.mont...@gmail.com,Candlestick Park],
Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
Metropolitan Stadidum],
Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High Stadium],
Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High
Stadium],
Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
Louisiana Superdome],
Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
Cowboy Stadium]}

print(Qb_Dict[Elway],\n)# print a dictionary entry

In the above the wrong Elway entry, the second one, where the first
name is Ed, is getting printed. I just added that second Elway row to
see how it would handle duplicates and the results are interesting, to
say the least.

2) Is there a way to print out the actual value of the key, like
Montana would be 0, Tarkington would be 1, etc?

A dictionary is simply a Key:Value store and keys are unique.  You're 
overwriting your first Elway entry with the second one when it's being 
captured. If you want to keep duplicate key values you'll need to 
re-look at what data structure you want to use, you can keep using a 
dictionary but then you'll need to change the value side of it perhaps 
like `{key: {key: value, key: value}}` so you end up with `{'Elway': 
{'John': [tel_num, email, home_ground], 'Ed': [tel_num, email, 
home_ground]}}` or some other implementation specific to your requirements.


As for your second question, the value of the key is a hash. So to get 
the value, you'll need to find what hashing algorithm is used by default 
for dictionaries and use that to get the value of it yourself.


--

Christian Witts
Python Developer
//
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3 dictionary questions

2011-11-23 Thread Wayne Werner
On Wed, Nov 23, 2011 at 7:04 AM, Cranky Frankie cranky.fran...@gmail.comwrote:

 In playing around with Pyton 3 dictionaries I've come up with 2 questions

 1) How are duplicate keys handled? For example:

 Qb_Dict = {Montana: [Joe, Montana, 415-123-4567,
 joe.mont...@gmail.com,Candlestick Park],
 Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
 Metropolitan Stadidum],
 Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
 Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High
 Stadium],
 Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High
 Stadium],
 Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
 Louisiana Superdome],
 Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
 Cowboy Stadium]}

 print(Qb_Dict[Elway],\n)# print a dictionary
 entry

 In the above the wrong Elway entry, the second one, where the first
 name is Ed, is getting printed. I just added that second Elway row to
 see how it would handle duplicates and the results are interesting, to
 say the least.

 2) Is there a way to print out the actual value of the key, like
 Montana would be 0, Tarkington would be 1, etc?


I'm not sure about #1, but I can tell you about #2.

Dictionaries are not ordered, so you have absolutely no guarantee which
order they'll appear in when you print them out, or if you iterate over the
dictionary. If you want to maintain some type of order you have a few
options. First, store the keys in a list, which does maintain order:

keys = ['Elway', 'Montana', ... ]

Then you would do something like:

Qb_Dict[keys[0]]

(As a slight aside, I'll direct you to PEP 8 which is the Python style
guide which contains things like naming conventions. If you want your code
to look Pythonic, you should take a look there.)

If you just want them to be sorted, you can run sorted on the keys()
collection from the dictionary:

for key in sorted(Qb_Dict.keys()):
print(Qb_Dict[key])

In Python 3 this will only work if your collection contains comparable
types - if you have {1:'Hello', 'Goodbye':2} then you'll get a TypeError
when it tries to compare 1 and 'Goodbye'

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3 dictionary questions

2011-11-23 Thread Peter Otten
Cranky Frankie wrote:

 In playing around with Pyton 3 dictionaries I've come up with 2 questions
 
 1) How are duplicate keys handled? For example:
 
 Qb_Dict = {Montana: [Joe, Montana, 415-123-4567,
 joe.mont...@gmail.com,Candlestick Park],
 Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
 Metropolitan Stadidum],
 Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
 Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High
 Stadium], Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile
 High Stadium],
 Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
 Louisiana Superdome],
 Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
 Cowboy Stadium]}
 
 print(Qb_Dict[Elway],\n)# print a dictionary
 entry
 
 In the above the wrong Elway entry, the second one, where the first
 name is Ed, is getting printed. I just added that second Elway row to
 see how it would handle duplicates and the results are interesting, to
 say the least.

The last one always wins. Perhaps it becomes clearer if you think of

d = {1:1, 1:2}

as syntactic sugar for

d = dict()
d[1] = 1
d[1] = 2

If you want to allow for multiple values per key use a list as the value and 
append to that:

 d = {}
 for k, v in [(1, 1), (2, 2), (1, 3)]:
... d.setdefault(k, []).append(v)
...
 d
{1: [1, 3], 2: [2]}

 2) Is there a way to print out the actual value of the key, like
 Montana would be 0, Tarkington would be 1, etc?

No, the actual key *is* Montana or Tarkington. The dictionary does not 
record the insertion order. 
There is a collections.OrderedDict, but I recommend that you don't try out 
that until you have grokked the builtin dict. As a rule of thumb there are 
less usecases for an OrderedDict than you think ;)


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sensing EOF in Python 3.1

2011-11-23 Thread Cranky Frankie
I'm reading in a pickled file. The program works but I'm having
trouble sensing end of file. Here's the program:

#
# pickle_in.py
# program to read in a pickled file
#
# Frank L. Palmeri
#

import pickle   # import the pickle module
pickle_file = open(d:/Work/pickle_file, rb) # open the pickled input file

read_file = pickle.load(pickle_file)# read the first input record

new_list=[] # create a new empty list

while pickle_file:  # loop until end of file
for i in range(0, 4):   # iterate for each field
new_list.append(read_file[i])   # append each field to
the new list
i = i + 1   # increment loop counter
print(new_list) # print the input
record from the new list
new_list=[] # initialize the new
list for the next record
read_file = pickle.load(pickle_file)# read the next record
in the input file


here's the error:

Traceback (most recent call last):
  File D:\MyDocs\Python\pickle_in.py, line 21, in module
read_file = pickle.load(pickle_file)# read the next record
in the input file
  File D:\Python31\lib\pickle.py, line 1365, in load
encoding=encoding, errors=errors).load()
EOFError







-- 
Frank L. Cranky Frankie Palmeri
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to shorten this code using classes?

2011-11-23 Thread Mic

Hi.
I have written a simple GUI program. It works just like it is intended to 
do, but there
is a problem, I feel like I could make it shorter. I thought of using 
classes instead of

doing it the way I have done.

Here is my code:

from tkinter import*

button1_color=green
button1_value=False

button2_color=green
button2_value=False


class Window(Frame):
   def __init__(self,master):
   super (Window,self).__init__(master)
   self.grid()
   self.create_widgets()

   def create_widgets(self):

   #Creates hello button1
   self.hello_bttn1=Button(self,bg=button1_color, text=Hi_1,
command=self.button1_clicked)
   self.hello_bttn1.grid()

   #Creates hello button2
   self.hello_bttn2=Button(self,bg=button2_color, text=Hi_1,
command=self.button2_clicked)
   self.hello_bttn2.grid()



   def button1_clicked(self):
This method runs if button one is clicked

   def change_button1_value():
   global button1_value
   button1_value=not button1_value

   change_button1_value()

   if button1_value:

   self.hello_bttn1.configure(bg=red, text=Hi_2)

   def change_button1_color_red():
   global button1_color
   button1_color=(red)
   change_button1_color_red()




   else:
   self.hello_bttn1.configure(bg=green, text=Hi_1)




   def change_button1_color_green():
   global button1_color
   button1_color=(green)
   change_button1_color_green()

   #-

   def button2_clicked(self):
   This method runs if button two is clicked

   def change_button2_value():
   global button2_value
   button2_value=not button2_value

   change_button2_value()

   if button2_value:

   self.hello_bttn2.configure(bg=red, text=Hi_2)



   def change_button2_color_red():
   global button2_color
   button2_color=(red)
   change_button2_color_red()




   else:
   self.hello_bttn2.configure(text=Hi_1, bg=green)




   def change_button2_color_green():
   global button2_color
   button2_color=(green)
   change_button2_color_green()




As you can button1_clicked and button2_clicked are very similiar. Imagine
that I would use more buttons than just the two that I am using now.

It would be a lot of functions then, one for each button. How do I 
accomplish

the same thing as my code does now, but using one function for all buttons
instead of one function for each button? Is it possible?

I hope these questions aren't stupid.

Thank you for your time!


Mic














root=Tk()
root.title(Test)
root.geometry(200x200)
app=Window(root)
root.mainloop()

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sensing EOF in Python 3.1

2011-11-23 Thread Peter Otten
Cranky Frankie wrote:

 I'm reading in a pickled file. The program works but I'm having
 trouble sensing end of file. Here's the program:
 
 #
 # pickle_in.py
 # program to read in a pickled file
 #
 # Frank L. Palmeri
 #
 
 import pickle   # import the pickle module
 pickle_file = open(d:/Work/pickle_file, rb) # open the pickled input
 file
 
 read_file = pickle.load(pickle_file)# read the first input
 record
 
 new_list=[] # create a new empty list
 
 while pickle_file:  # loop until end of file
 for i in range(0, 4):   # iterate for each field
 new_list.append(read_file[i])   # append each field to
 the new list
 i = i + 1   # increment loop counter
 print(new_list) # print the input
 record from the new list
 new_list=[] # initialize the new
 list for the next record
 read_file = pickle.load(pickle_file)# read the next record
 in the input file
 
 
 here's the error:
 
 Traceback (most recent call last):
   File D:\MyDocs\Python\pickle_in.py, line 21, in module
 read_file = pickle.load(pickle_file)# read the next record
 in the input file
   File D:\Python31\lib\pickle.py, line 1365, in load
 encoding=encoding, errors=errors).load()
 EOFError

How did you write the data into the pickle file? The normal approach is to 
write all your data in one step, e. g. (all code snippets untested)

# write list
with open(filename, wb) as out:
pickle.dump(list_of_records, out)

You can then read back all records with

# read list
with open(filename, rb) as instream:
list_of_records = pickle.load(instream)

A second approach is also possible, but not appropriate for a newbie:

# write list entries
with open(filename, wb) as out:
for record in list_of_records:
pickle.dump(record, out)

# read list entries to rebuild the list
list_of_records = []
with open(filename, rb) as instream:
while True:
try: 
record = pickle.load(instream)
except EOFError:
break
else:
list_of_records.append(record)

By the way

 new_list=[]
 for i in range(0, 4):
 new_list.append(read_file[i])
 i = i + 1

- Here the for-loop is taking care of the value of i, you don't have to 
increment it manually. 

- A simpler way to achieve the same is

new_list = read_file[:4]


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Physics Engine

2011-11-23 Thread Christopher King
I'm more of a beginner, so it would be nice for it to work with Livewires.
It doesn't need to be that complex (no need for air pressure, elasticity,
or energy.) I just need enough that I will stay on the ground and that when
I swing sprites around on a rope, they swing in a circle, not a square. A
good reference for making one would  be good to.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to shorten this code using classes?

2011-11-23 Thread Peter Otten
Mic wrote:

 Hi.
 I have written a simple GUI program. It works just like it is intended to
 do, but there
 is a problem, I feel like I could make it shorter. I thought of using
 classes instead of
 doing it the way I have done.
 
 Here is my code:
 
 from tkinter import*
 
 button1_color=green
 button1_value=False
 
 button2_color=green
 button2_value=False
 
 
 class Window(Frame):
 def __init__(self,master):
 super (Window,self).__init__(master)
 self.grid()
 self.create_widgets()
 
 def create_widgets(self):
 
 #Creates hello button1
 self.hello_bttn1=Button(self,bg=button1_color, text=Hi_1,
 command=self.button1_clicked)
 self.hello_bttn1.grid()
 
 #Creates hello button2
 self.hello_bttn2=Button(self,bg=button2_color, text=Hi_1,
 command=self.button2_clicked)
 self.hello_bttn2.grid()
 
 
 
 def button1_clicked(self):
  This method runs if button one is clicked
 
 def change_button1_value():
 global button1_value
 button1_value=not button1_value
 
 change_button1_value()
 
 if button1_value:
 
 self.hello_bttn1.configure(bg=red, text=Hi_2)
 
 def change_button1_color_red():
 global button1_color
 button1_color=(red)
 change_button1_color_red()
 
 else:
 self.hello_bttn1.configure(bg=green, text=Hi_1)
 
 def change_button1_color_green():
 global button1_color
 button1_color=(green)
 change_button1_color_green()
 
 #-
 
 def button2_clicked(self):
 This method runs if button two is clicked
 
 def change_button2_value():
 global button2_value
 button2_value=not button2_value
 
 change_button2_value()
 
 if button2_value:
 
 self.hello_bttn2.configure(bg=red, text=Hi_2)
 
 def change_button2_color_red():
 global button2_color
 button2_color=(red)
 change_button2_color_red()
 
 else:
 self.hello_bttn2.configure(text=Hi_1, bg=green)
 
 def change_button2_color_green():
 global button2_color
 button2_color=(green)
 change_button2_color_green()

 root=Tk()
 root.title(Test)
 root.geometry(200x200)
 app=Window(root)
 root.mainloop()

 As you can button1_clicked and button2_clicked are very similiar. Imagine
 that I would use more buttons than just the two that I am using now.
 
 It would be a lot of functions then, one for each button. How do I
 accomplish
 the same thing as my code does now, but using one function for all buttons
 instead of one function for each button? Is it possible?

I chose to ignore the using classes part. If you like you can turn the 
button_clicked() function into a method of a subclass of Button. You can 
also move the Button configuration done in create_widgets() into the 
__init__() method of that subclass. 

import tkinter as tk
from functools import partial

def button_clicked(button):
if button[bg] == green:
button.configure(bg=red, text=Hi 2)
else:
button.configure(bg=green, text=Hi 1)

class Window(tk.Frame):
def __init__(self, master):
super (Window, self).__init__(master)
self.grid()
self.create_widgets()

def create_widgets(self):
for _ in range(2):
button = tk.Button(self)
command = partial(button_clicked, button)
button[command] = command
button.grid()
command()

root = tk.Tk()
root.title(Test)
root.geometry(200x200)
app = Window(root)
root.mainloop()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to shorten this code using classes?

2011-11-23 Thread James Reynolds
On Wed, Nov 23, 2011 at 10:35 AM, Mic o0m...@hotmail.se wrote:

 Hi.
 I have written a simple GUI program. It works just like it is intended to
 do, but there
 is a problem, I feel like I could make it shorter. I thought of using
 classes instead of
 doing it the way I have done.

 Here is my code:

 from tkinter import*

 button1_color=green
 button1_value=False

 button2_color=green
 button2_value=False


 class Window(Frame):
   def __init__(self,master):
   super (Window,self).__init__(master)
   self.grid()
   self.create_widgets()

   def create_widgets(self):

   #Creates hello button1
   self.hello_bttn1=Button(self,**bg=button1_color, text=Hi_1,
 command=self.button1_clicked)
   self.hello_bttn1.grid()

   #Creates hello button2
   self.hello_bttn2=Button(self,**bg=button2_color, text=Hi_1,
 command=self.button2_clicked)
   self.hello_bttn2.grid()



   def button1_clicked(self):
This method runs if button one is clicked

   def change_button1_value():
   global button1_value
   button1_value=not button1_value

   change_button1_value()

   if button1_value:

   self.hello_bttn1.configure(bg=**red, text=Hi_2)

   def change_button1_color_red():
   global button1_color
   button1_color=(red)
   change_button1_color_red()




   else:
   self.hello_bttn1.configure(bg=**green, text=Hi_1)




   def change_button1_color_green():
   global button1_color
   button1_color=(green)
   change_button1_color_green()

   #-**

   def button2_clicked(self):
   This method runs if button two is clicked

   def change_button2_value():
   global button2_value
   button2_value=not button2_value

   change_button2_value()

   if button2_value:

   self.hello_bttn2.configure(bg=**red, text=Hi_2)



   def change_button2_color_red():
   global button2_color
   button2_color=(red)
   change_button2_color_red()




   else:
   self.hello_bttn2.configure(**text=Hi_1, bg=green)




   def change_button2_color_green():
   global button2_color
   button2_color=(green)
   change_button2_color_green()




 As you can button1_clicked and button2_clicked are very similiar. Imagine
 that I would use more buttons than just the two that I am using now.

 It would be a lot of functions then, one for each button. How do I
 accomplish
 the same thing as my code does now, but using one function for all buttons
 instead of one function for each button? Is it possible?

 I hope these questions aren't stupid.

 Thank you for your time!


 Mic














 root=Tk()
 root.title(Test)
 root.geometry(200x200)
 app=Window(root)
 root.mainloop()

 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor









Button 1 and Button 2 already are classes, so unless you need to subclass,
you are simply being redundant.

A couple things first: don't use globals all over the place unless you want
to have a serious headache.

You have a wicked about of redundancy in your code, you don't need an
object oriented approach to condense, but it can be helpful at times.

However, as far as your question. For the two functions, you could subclass
Button and add them to your new Button object:

(untested)


class MyButton(Button):
button_color=green
button_value=False

def __init__(self, *args, **kwargs):
super(Button, self).__init__(*args, **kwargs)

def change_value_and_color(self):
self.button_value = not self.button_value
if self.button_value:
self.button_color=red
self.configure(bg=self.button_color, text=Hi_2)
else:
self.button_color=green
self.hello_bttn1.configure(bg=self.button_value, text=Hi_1)

def button_clicked(self):
 This method runs if button one is clicked
self.change_value_and_color()


I left in the button_clicked method, but as you can see it is utterly
pointless to have it. Just rename your first function and call it directly.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sensing EOF in Python 3.1

2011-11-23 Thread Cranky Frankie
From: Peter Otten __pete...@web.de wrote:
snip
How did you write the data into the pickle file? The normal approach is to
write all your data in one step, e. g. (all code snippets untested)

Thanks Peter, that was it. I was treating pickle like standard file
i/o when it's not that at all.

The reason why I'm pickling is I'm trying to include information on
Python data structures in the presentaton I'm preparing.

Here are the two programs that now work correctly together:

import pickle
pickle_file = open(d:/Work/pickle_file, wb)

Qb_dict = {Montana: [Joe, Montana, 415-123-4567,
joe.mont...@gmail.com,Candlestick Park],
Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
Metropolitan Stadidum],
Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High Stadium],
Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High
Stadium],
Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
Louisiana Superdome],
Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
Cowboy Stadium]}

pickle.dump(Qb_dict, pickle_file)

pickle_file.close()



#
# pickle_in.py
# program to read in a pickled file
#
# Frank L. Palmeri
#

import pickle   # import the pickle
module
pickle_file = open(d:/Work/pickle_file, rb) # open the pickled file

read_list = pickle.load(pickle_file)# read the first pickled row

print(read_list)# print the input row from
the pickled file

pickle_file.close() # close the pickled file




-- 
Frank L. Cranky Frankie Palmeri
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Template class and class design on concrete example xl2csv writer

2011-11-23 Thread Karim

Hello All,

I have the following code and I am quite satisfied with its design BUT I 
have the feeling I can do better.
Basically the, main() execute the program (I did not put the parsing of 
arguments function). I am opening
an Excel document and writing content in a CSV one w/ different format. 
The design is an abstract template
class XLWriter, and derived  'Xl2Csv', 'Xl2Scsv', 'Xl2text' classes to 
write the correct ASCII DOCUMENT to correct format.
The property hook method file_format is implement in these classes and 
return an object of type 'XlCsvFileFormat' or 'XlTabFileFormat'.
It allows to put the right file extension and delimiter. These class are 
derived from standard csv.excel and csv.excel_tab.
At last a Factory class MakeXlWriter has the job to create the correct 
writer.


For now I did not add a strategy pattern which usually goes with the 
Template pattern.


Except from that all better design or others critics will be welcome.


Regards
karim

___

from __future__ import print_function

import sys, os, argparse, csv, xlrd

__all__  = ['main', 'Xl2CsvError', 'XLWriter', 'XlCsvFileFormat', 
'XlTabFileFormat', 'Xl2Csv', 'Xl2Scsv', 'Xl2text', 'MakeXlWriter']



class Xl2CsvError(Exception):
The exception class to manage the internal program errors.
pass

class XlWriter(object):
Abstract template class.
def __init__(self, xlfilename=None, sheets=None):
Initializer.
if self.__class__.__name__ == 'XlWriter':
raise TypeError('Abstract template Class XlWriter could not 
be instanciated directly!')


if not xlfilename:
raise Xl2CsvError('Please provide a non empty file name!')
else:
self._source_name = xlfilename

self._book = xlrd.open_workbook(xlfilename)

if sheets is not None:
if isinstance(sheets[0], int):
self._selected_sheets = 
[self._book.sheet_by_index(sheetnum-1) for sheetnum in sheets]

elif isinstance(sheets[0], str):
try:
self._selected_sheets = 
[self._book.sheet_by_name(sheetname) for sheetname in sheets]

except xlrd.biffh.XLRDError, e:
print('{0} in file document {1}'.format(e, xlfilename))
sys.exit(1)
else:
raise Xl2CsvError('Sheets element type not recognized!')
else:
self._selected_sheets = self._book.sheets()

def write(self):
The file extraction public method.

for sheet in self._selected_sheets:
xlfilename = '{sheet}{ext}'.format(sheet=sheet.name, 
ext='.'+self.file_format.extension.lower())

try:
writer = csv.writer(open(xlfilename, 'wb'), 
delimiter=self.file_format.delimiter)
print(Creating csv file '{file}' for sheet '{sheet}' 
contained in document {src} format(
   sheet=sheet.name, file=xlfilename, 
src=self._source_name), end=' ')

for row in xrange(sheet.nrows):
writer.writerow(sheet.row_values(row))
print('Done.')
except csv.Error, e:
print(e)
return 1

return 0

@property
def file_format(self):
Hook method. Need to implement in derived classes.

Should return an XLAsciiFileFormat object to get file extension 
and inner delimiter.


pass

class XlCsvFileFormat(csv.excel):
Add file extension to the usual properties of Excel-generated 
CSV files.

extension = 'CSV'

class XlTabFileFormat(csv.excel_tab):
Add file extension to the usual properties of Excel-generated 
TAB delimited files.

extension = 'TXT'

class Xl2Csv(XlWriter):
@property
def file_format(self):
Hook factory method
return  XlCsvFileFormat()

class Xl2Scsv(XlWriter):
@property
def file_format(self):
Hook factory method
_format = XlCsvFileFormat()
_format.extension = 'SCSV'
_format.delimiter = ';'
return _format

class Xl2Text(XlWriter):
@property
def file_format(self):
Hook factory method
return  XlTabFileFormat()

class MakeXlWriter(object):
Factory class for XLWriter objects.

@staticmethod
def make(xlfilename=None, sheets=None, extension='CSV'):
if extension == TXT:
   return Xl2Text(xlfilename=xlfilename, sheets=sheets)
elif extension == SCSV:
   return Xl2Scsv(xlfilename=xlfilename, sheets=sheets)
elif extension == CSV:
   return Xl2Csv(xlfilename=xlfilename, sheets=sheets)

def main():
Main of this application
args = _process_command_line()
args.xl.close()
writer = MakeXlWriter.make(xlfilename=args.xl.name, 
sheets=args.sheets, extension=args.ext)

return 

Re: [Tutor] sensing EOF in Python 3.1

2011-11-23 Thread Wayne Werner
On Wed, Nov 23, 2011 at 12:03 PM, Cranky Frankie
cranky.fran...@gmail.comwrote:

 [...]
 The reason why I'm pickling is I'm trying to include information on
 Python data structures in the presentaton I'm preparing. [...]


In your context why not just use modules?


 # data.py
Qb_dict = {Montana: [Joe, Montana, 415-123-4567,
joe.mont...@gmail.com,Candlestick Park],
Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com,
Metropolitan Stadidum],
Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium],
Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High
Stadium],
Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High
Stadium],
Manning: [Archie,504-888-1234, archie.mann...@gmail.com,
Louisiana Superdome],
Staubach: [Roger,214-765-8989, roger.staub...@gmail.com,
Cowboy Stadium]}

# program.py
from data import Qb_dict
print(Qb_dict)

Then you can put whatever comments or data you want. Just make sure that
you don't name your data.py file the same as something built-in. It's
pretty horrible when you try to 'import random' and it doesn't randint() or
anything else that you're looking for.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic class loading question

2011-11-23 Thread Emile van Sebille

On 11/22/2011 11:25 AM Cranky Frankie said...
snip


quarterbacks = []   # Create an empty object list


In the interest of preferred techniques, your loop will be more pythonic 
when you write this part...




len_Qb_list = len(Qb_list)  # Get the lenght of the list of
  lists which is the
 #number of rows in the input data

for i in range(0, len_Qb_list): # Iterate for the number of rows

 nq = Qb(*Qb_list[i])# Create an instance of class Qb called 
nq
 #and populate each field
 quarterbacks.append(nq) # Append an instance of object
nq into object list quarterbacks
 i = i + 1   # Iterate for each row in Qb_list


...like this...

for this_qb in Qb_list:# Iterate over Qb_list
quarterbacks.append(Qb(*this_qb))  # append Qb instance to quarterbacks

...or even drop the quarterbacks declaration above...

quarterbacks = [Qb(*this_qb) for this_qb in Qb_list

Emile




print (quarterbacks[3].phone)   # Print an item from the object
list quarterbacks
print (Qb_list[3][2])   # Print the same object from the
original list of lists







___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to shorten this code using classes?

2011-11-23 Thread Mic

I chose to ignore the using classes part. If you like you can turn the
button_clicked() function into a method of a subclass of Button. You can
also move the Button configuration done in create_widgets() into the
__init__() method of that subclass.


import tkinter as tk
from functools import partial

def button_clicked(button):
   if button[bg] == green:
   button.configure(bg=red, text=Hi 2)
   else:
   button.configure(bg=green, text=Hi 1)

class Window(tk.Frame):
   def __init__(self, master):
   super (Window, self).__init__(master)
   self.grid()
   self.create_widgets()

   def create_widgets(self):
   for _ in range(2):
   button = tk.Button(self)
   command = partial(button_clicked, button)
   button[command] = command
   button.grid()
   command()

root = tk.Tk()
root.title(Test)
root.geometry(200x200)
app = Window(root)
root.mainloop()


___

A very elegant solution. Much better than my previous one. However, I am a 
bit unfamiliar with your way of
coding, I assume you are used to a version other than Python 3.2? Because, 
never before have I seen either

of those
import tkinter as tk
from functools import partial

I also wonder, if I implement your solution, is there anyway I can place the 
buttons in the program as I would like, or will they be played in a 
straight, vertical row

always?

Also, assume that I have a already have a window with a button in it. If you 
press this button, this window is supposed to open.
So, if I press the button, will this window open? Because I created the 
previous window using

from tkinter import* and not import tkinter as tk.


I hope my English is understandable, because it is not my primary language.
Thanks for your help, it is greatly appreciated!




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sensing EOF in Python 3.1

2011-11-23 Thread Steven D'Aprano

Cranky Frankie wrote:

I'm reading in a pickled file. The program works but I'm having
trouble sensing end of file. Here's the program:

[...]

Traceback (most recent call last):
  File D:\MyDocs\Python\pickle_in.py, line 21, in module
read_file = pickle.load(pickle_file)# read the next record
in the input file
  File D:\Python31\lib\pickle.py, line 1365, in load
encoding=encoding, errors=errors).load()
EOFError


Seems to me that you have successfully found the end of file.

I'm not be facetious here. Easier to ask forgiveness afterwards than 
permission before hand is generally (but not necessarily always) the 
preferred way of coding things in Python. So instead of trying to 
predict the end of file ahead of time:


while some_hard_to_calculate_condition():
do_stuff_with_pickle()

you can catch the error instead:

try:
while True:  # Loop forever, until interrupted
do_stuff_with_pickle()
except EOFError:
# no more pickles, so we must be done
pass



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sensing EOF in Python 3.1

2011-11-23 Thread Steven D'Aprano

Cranky Frankie wrote:

From: Peter Otten __pete...@web.de wrote:
snip
How did you write the data into the pickle file? The normal approach is to
write all your data in one step, e. g. (all code snippets untested)

Thanks Peter, that was it. I was treating pickle like standard file
i/o when it's not that at all.


I don't understand what you mean by this.

Pickle does standard file I/O in the same way that opening a JPEG in an 
image view does standard file I/O: both programs read data from a file 
the standard, ordinary way, but expect data of a certain format. If you 
provide it too little data, you will get an EOF error. If you provide 
too much data, or messed up data, then you will some other error. But 
the file I/O is exactly the same. It's just that pickle, or your image 
viewer, handle it for you.




The reason why I'm pickling is I'm trying to include information on
Python data structures in the presentaton I'm preparing.


Pickling won't tell you anything about Python data structures. Pickling 
takes Python data structures, bashes them with a hammer until they stop 
wiggling, then runs them through a serialiser turning them into a stream 
of text or binary codes.


Pickles tell you only about pickles. You won't learn anything about 
(say) dicts by looking at a pickled dict except the bare fact that dicts 
can be pickled.


py import pickle
py d = {key: value, another key: 42}
py pickle.dumps(d)
(dp0\nS'another key'\np1\nI42\nsS'key'\np2\nS'value'\np3\ns.

I don't know what you expect to learn about dicts from that.



Here are the two programs that now work correctly together:

import pickle
pickle_file = open(d:/Work/pickle_file, wb)

Qb_dict = { ... contents of dict skipped ... }
pickle.dump(Qb_dict, pickle_file)
pickle_file.close()


Take note that you are pickling a dict. This is important later on.



#
# pickle_in.py
# program to read in a pickled file
#
# Frank L. Palmeri
#

import pickle# import the pickle module


Really? Wow! I thought import pickle meant sort the database!!! *wink*

Sarcasm aside, what else could import pickle mean other than import 
the pickle module? The comment adds absolutely nothing to the code. At 
best it is superfluous. At worst it is harmful, because code and 
comments have a regrettable tendency to get out of sync.


Every comment should carry its weight. If the code is particularly 
convoluted, you might write comments explaining *how* you do something, 
but generally the code speaks for itself regarding the how, so comments 
should explain *why* you do something. If a comment doesn't tell you 
something that the code doesn't, that you need to know (or at least 
should know). Otherwise it should be throw out into the back alley for 
the stray cats to eat.



pickle_file = open(d:/Work/pickle_file, rb) # open the pickled file
read_list = pickle.load(pickle_file)# read the first pickled row


And this is what I'm talking about. It does NOT read the first pickled 
row. Pickles don't have rows. In this case, you are reading the first 
and only pickled object, which happens to be a dict.




print(read_list)  # print the input row from the pickled file
pickle_file.close()   # close the pickled file


Every comment in your second file is either unnecessary, or wrong. This 
is a good example of the need to comment smart rather than comment 
hard.


# Bad:
i += 1  # Add one to i.

# Good:
i += 1  # Adjust i for one-based indexing.


--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor