Re: [Tutor] try except continue

2005-07-28 Thread tpc247
hi Danny, well from my previous message:

ideally what I'd like is for my procedural program, when it runs
through its steps and encounters an error, to log the error and pick
up where it left off and keep going.

so for the execution of someProcedure(), I want it to print the error
and continue running through the rest of someProcedure().  Is this
possible ?

On 7/28/05, Danny Yoo <[EMAIL PROTECTED]> wrote:
> 
> 
> Hi Tpc,
> 
> What did you expect to happen when we hit the continue statement?  It'll
> help to know what you wanted to happen, so that we can better understand
> the problem.
> 
> 
> According to:
> 
> http://www.python.org/doc/ref/continue.html
> 
> 'continue' is only effective if we're in a loop, so the error message is
> perfectly true.  So I think we need to know more about what you are trying
> to do.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try except continue

2005-07-28 Thread tpc247
hi Alan and Danny,

I think I understand what you guys are saying.  I don't believe I am
ignoring the error.  Ideally what I'd like is for the procedural
program to run through its steps and if it encounters an error, to log
the error and pick up where it left off and keep going.  I gather you
think that is bad practice, but how bad ?  If I log the error so that
I can go back and decipher what input caused, say, the
UnboundLocalError, and keep running the rest of my program, then I
feel that is better than running through the program and upon
encountering an error, stopping the program dead in its tracks.  My
program parses documents from two different sources, and currently if
the template for one source changes, then the other source's documents
are not parsed.  What I'd like is if an error is encountered, the
input (document) that caused the error is logged, and the rest of the
documents are parsed without stopping the "assembly line."  I see the
continue statement as a way for me to do this, and thus intimately
linked with exception handling.  I have a hard time figuring out why
you think this is bad practice.


On 7/28/05, Danny Yoo <[EMAIL PROTECTED]> wrote:

> Hi Tpc,
> 
> I think there's some confusion about the role of 'continue'; it's doesn't
> have anything to do with exception handling.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] try except continue

2005-08-01 Thread tpc247
hi guys, so I've been running through Alan's code, and for a while I
suspected that the try block must be the first line of code after the
loop in order to be executed.  The reason I say this is I wanted to
see for myself Alan's assertion that the continue skips to the next
iteration, instead of continuing with the rest of the try block, so I
did the following:

def f():
if error:
raise ValueError
else:
print "I'm in f()"

def g():
print "I'm in g()"


def h():
error = True
print "error is: ", error
n = 5
while n:
print "n is: ", n
n -= 1
try:
f()
g()
except ValueError:
error = False
continue

and I got the following as output:

>>> h()
error is:  True
n is:  5
n is:  4
n is:  3
n is:  2
n is:  1

I gathered that since I didn't see the output of f() and g(), then
those two functions must have never executed, and thus the try block
must have never executed.  However, when I moved the try block to be
the first line after the loop:

def h():
error = True
print "error is: ", error
n = 5
while n:
try:
f()
g()
except ValueError:
error = False
continue
print "n is: ", n
n -= 1

I got the following as output:

>>> h()
error is:  True

Traceback (most recent call last):
  File "", line 1, in -toplevel-
h()
  File "", line 9, in h
except ValueError:
KeyboardInterrupt

and I actually had to press Ctrl-C to stop the never terminating
program.  I simply wanted to confirm Alan's assertion that continue
will cause the loop to skip to the next iteration, but it seems I
can't seem to get my f() and g() to print even though they were able
to before.  Am I doing something wrong ?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] don't repeat yourself; question about code optimization

2007-07-20 Thread tpc247

dear fellow Python enthusiasts:

in the last year I have been experimenting with Python, and I set out to
create a function that, given a number of items and a maximum number of
items per row, would generate a table of rows of items.  However, there is
one part where I believe I violate the prime directive of coding, which is
not to repeat yourself:

class Table_Creator(object):
   def __init__(self, given_num_of_items, max_num_of_items_per_row):
   self.total_num_of_items = range(given_num_of_items)
   self.max_num_of_items_per_row = max_num_of_items_per_row

   def create_grid(self):
   table = []
   row = []
   count = 0
   while self.total_num_of_items:
   row.append(self.total_num_of_items.pop(0))
   count += 1
   if (not self.total_num_of_items) or (count ==
self.max_num_of_items_per_row):
   table.append(tuple(row))
   row = []
   count = 0
   return table

as you can see, I repeat the expressions "row = []" and "count = 0", and I
would like to know if there is something I can do to avoid repetition in
this case.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] don't repeat yourself; question about code optimization

2007-07-22 Thread tpc247

On 7/20/07, Bob Gailer <[EMAIL PROTECTED]> wrote:


Take advantage of slicing:
   def create_grid(self):
   table = []
   for i in range(0, len(self.total_num_of_items),
self.max_num_of_items_per_row):
 table.append(tuple(self.total_num_of_items[i : i +
self.max_num_of_items_per_row]))
   return table



simply amazing.  Thank you.

OK - to address your original question:


def create_grid(self):
table = []
while self.total_num_of_items:
row = []
count = 0
while count < self.max_num_of_items_per_row and
self.total_num_of_items:
row.append(self.total_num_of_items.pop(0))
count += 1
table.append(tuple(row))
return table



At first I  regarded you with quiet awe, but then the nitpick in me saw the
two "while self.total_num_of_item" statements, and I was less pleased.
However, I see this as a doable challenge you have given me, and I will
attempt to optimize your revisions.  Thanks again.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] don't repeat yourself; question about code optimization CORRECTION

2007-07-29 Thread tpc247
On 7/23/07, Bob Gailer <[EMAIL PROTECTED]> wrote:
>
> A correction to the code at the end. The test of self.total_num_of_items
> should precede the pop(0)



Bob, I spent today studying what you've been telling me and I put the
finishing touches to make your code pass my battery of tests.  It still is
repetitive, i.e., table.append(tuple(row)), but I've found guidance in what
Alan had to say about code readability and easy maintenance, and am no
longer going to press the matter:

class Table_Creator(object):
def __init__(self, total_num_of_items, max_num_of_items_per_row):
self.given_items = range(total_num_of_items)
self.max_num_of_items_per_row = max_num_of_items_per_row

def create_grid(self):
table = []
while True:
row = []
while len(row) < self.max_num_of_items_per_row:
if not self.given_items:
if row:
table.append(tuple(row))
return table
row.append(self.given_items.pop(0))
table.append(tuple(row))
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] don't repeat yourself; question about code optimization

2007-07-29 Thread tpc247
On 7/23/07, Alan Gauld <[EMAIL PROTECTED]> wrote:

>
> The prime directive of coding is make it readable!
> The DRY principle is just that a principle. If repeating makes for
> more maintainable or readable code then repeat yourself.
>
> Remember 80% of the cost of software is in maintenance not initial
> development. DRY is one way to improve maintainablility
> PS The most serious problem with your code from my perpspective
> is that your variable names are way too long. That affects maintenance
> and readability more that the repetition (and in the case of email it
> causes line wrapping that makes it even worse!)
>
> Finally the class is not a good class in an OOP sense since it is
> nearly a verb.
> It is better done as a simple function in my view, just pass in the
> parameters to
> the create method. Like this:
>
> def create_table(num_items, row_size):
> start = 0
> table = []
> num_rows = num_items/row_size
> for n in range(num_rows):
> row = [num for num in range(start,start+row_size)]
> table.append(tuple(row))
> start += row_size
> return table
>
> Or better still build a table class that knows how to create
> itself, but also knows how to maniplulate itself too - doing whatever
> it is you intend doing to the table you just created! This reflects
> another
> programming "rule" - the law of demeter" - one of the fundamentals of
> OOP.



Alan, I spent today going over what you took the time to patiently
illustrate to me, and I believe I learned the following things:
- code readability and ease of maintenance are the primary goals of a
computer programmer
- classes that are very nearly verbs should be converted to functions,
unless you can write a class that knows how to create and manipulate itself,
following the law of demeter

About the last bit of code, where you propose to create the table using list
comprehension, I did want to capture partial rows, so I put the finishing
touches to your work so it could.  When I subjected the code to a battery of
tests, it failed in the following way:

def create_table(num_items, row_size):
start = 0
table = []
num_rows = (num_items/row_size) + (num_items%row_size)
for n in range(num_rows):
row = [num for num in range(num_items)[start:start+row_size]]
table.append(tuple(row))
start += row_size
return table

def test_harness():
assert create_table(3, 1) == [(0,), (1,), (2,)]
assert create_table(4, 1) == [(0,), (1,), (2,), (3,)]
assert create_table(1, 2) == [(0,)]
assert create_table(2, 2) == [(0, 1)]
assert create_table(4, 2) == [(0, 1), (2, 3)]
assert create_table(5, 2) == [(0, 1), (2, 3), (4, )]
assert create_table(5, 3) == [(0, 1, 2), (3, 4)]
assert create_table(7, 4) == [(0, 1, 2, 3), (4, 5, 6)]

assert create_table(5, 3) == [(0, 1, 2), (3, 4)]
AssertionError

I know that my method of calculating the number of rows is faulty, but I'm
not sure how to correct it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] passing form data into a class

2007-07-30 Thread tpc247
dear fellow Python enthusiasts, let's say I have a dictionary of keys and
values obtained from a form submitted by a user.  For each submitted form I
will create the Application and Candidate classes, and I want to be able to
call Application(Candidate(**submitted_data)).display() to create an html
representation of the user submitted data.  Depending on the applicant's
preferences and location, the number of fields on the form, and thus the
size of this dictionary, is variable, and not all fields are required.  I
seem to recall a setargs function in Python that would take any argument
passed into a class and set that argument as a member variable in a class.
A Google search turned up no such construct, so here I am asking you, is
there a way for me to create a class that accepts a dictionary of submitted
data and uses each key ad value to create a corresponding member variable ?
The current way I do this is with a very long argument list, and line by
line:

class Candidate(object):
def __init__(self, full_name, address_line_1, city, postal_code, email,
desired_program, telephone=None, disabled=None, can_receive_media=None,
media_sent_to=None, ...):
self.full_name = full_name
self.address_line_1 = address_line_1
self.city = city
self.postal_code = postal_code
self.email = email
self.desired_program = desired_program

class Application(object):
def __init__(self, candidate):
self.candidate = candidate

def display(self):
pass
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unicode and character sets

2007-08-16 Thread tpc247
dear fellow Python enthusiasts,

I recently wrote a script that grabs a file containing a list of ISO defined
countries and creates an html select element.  That's all well and good, and
everything seems to work fine, except for one little nagging problem:

http://en.wikipedia.org/wiki/Aland_Islands

I use the Wikipedia url because I'm conscious of the fact that people
reading this email might not be able to see the character I am having
trouble displaying correctly, the LATIN CAPITAL LETTER A WITH RING ABOVE
character.  After reading the following article:

http://www.joelonsoftware.com/articles/Unicode.html

I realize the following: It does not make sense to have a string without
knowing what encoding it uses.  There is no such thing as plain text.

Ok.  Fine.  In Mozilla, by clicking on View, Character Encoding, I find out
that the text in the file I grab from:

http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/index.html

is encoded in ISO-8859-1.  So I go about changing Python's default encoding
according to:

http://www.diveintopython.org/xml_processing/unicode.html

and voila:

>>> import sys
>>> sys.getdefaultencoding()
'iso-8859-1'
>>>

BUT the LATIN CAPITAL LETTER A WITH RING ABOVE character still displays in
IDLE as \xc5 !  I can get the character to display correctly if I type:

print "\xc5"

which is fine if I am simply going to copy and paste the select element into
my html file.  However, I want to be able to dynamically generate the html
form page and have the character in question display correctly in the web
browser.  In case you're wondering, I've already done my due diligence to
ensure the character set is ISO-8859-1 in my web server as well as in the
html file:

- in my html file, I put in:

- I restarted apache after changing httpd.conf to add the line:
AddDefaultCharset ISO-8859-1

The problem, of course, is that if I run my script that creates the select
element in IDLE I continue to see the output:

\xc5land Islands

Am I doing something wrong ?

def create_bidirectional_dicts_from_latest_ISO_countries():
import urllib
ISO3166_FILE_URL = "
http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1-semic.txt
"
a2_to_name = {}
name_to_a2 = {}
file_obj = urllib.urlopen(ISO3166_FILE_URL)
for line in file_obj:
if line.startswith("This list") or line.isspace():
pass
else:
a_list = line.split(';')
ISO_name = a_list[0].title()
ISO_a2 = a_list[1].strip()
a2_to_name[ISO_a2] = ISO_name
name_to_a2[ISO_name] = ISO_a2
file_obj.close()
return a2_to_name, name_to_a2

def create_select_element_from_dict(name, a_dict, default_value=None):
parent_wrapper = "%s"
child_wrapper = "\tPlease select one\n%s"
element_template = "\t%s\n"
default_element = "\t%s\n"
a_str = ""
for key in sorted(a_dict.keys()):
if default_value and a_dict[key] == default_value:
a_str = a_str + default_element % (default_value, key)
a_str = a_str + element_template % (a_dict[key], key)
c_w_instance = child_wrapper % a_str
return parent_wrapper % (name, c_w_instance)

a2_to_name, name_to_a2 =
create_bidirectional_dicts_from_latest_ISO_countries()
a_select = create_select_element_from_dict("country", name_to_a2)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unicode and character sets

2007-08-16 Thread tpc247
On 8/16/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
>
>
> thanks, one of the good folks at metafiler provided the link to an
> excellent introductory article
>
>
correction: metafilter
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unicode and character sets

2007-08-16 Thread tpc247
On 8/16/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> [EMAIL PROTECTED] wrote:
>
> Good start!


thanks, one of the good folks at metafiler provided the link to an excellent
introductory article

I don't think this is necessary. Did it actually fix anything? Changing
> the default encoding is not recommended because it makes your scripts
> non-portable.


indeed, putting the sitecustomize.py script in site-packages did nothing to
help me generate a script that would print out the non-ASCII character in
IDLE, and, if what you say is correct, may very well introduce new problems.

In many cases IDLE will display the repr() of a string which shows any
> non-ascii character as a hexidecimal escape. It is actually the correct
> character. print does not use the repr() so it displays correctly.


ah, I see.  Any string not ASCII encoded, generated by my script in IDLE,
will be displayed as hexadecimal.  Essentially, I was in a round house
trying to find the corner !

No, actually you are doing great. This is correct output, it is just not
> displaying in the form you expect. The data is correct.


after reading your email, I wrote a follow-up script that wrote the
generated output to a file in my Apache document root, and eureka, I was
able to get the result I desired.  Thanks for your help.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] operating system key-bindings that call Python scripts

2007-08-20 Thread tpc247
I have a particular date time format I use for making entries in various
logs I maintain, and ideally what I'd like is for my operating system
(Windows or Linux) to recognize that every time I type, say, -'C' '1',
a Python script I wrote will execute and out will pop the current date time
in my desired format.  I want this to happen not just in my Xemacs text
editor buffer, but inside a textfield for, say, the Gmail application in
Mozilla, in Python IDLE, in the Google desktop search bar and at the command
line.  At LinuxWorld I asked three of the people from the San Francisco
Linux users group about doing this in Ubuntu, and here is what I could
ascertain:
*) the Apple OS is ideally suited to doing what you want, and necessitates
learning AppleScript.  In Windows or Linux it's a lot more complicated to
bind a sequence of keys to call a Python program that generates output in
any graphical window and, in fact, it may be impossible or more trouble than
it's worth
*) at the prompt you can execute the Python program to output the date time
in your desired format, but to do this in Gnome or KDE is a different story
*) within the browser environment you can write a Mozilla Firefox extension
that may allow you to call Python scripts, but this necessitates learning
XUL

Have any of you ever successfully engineered an operating system key-binding
that calls a Python script and directs the output where the cursor is in any
graphical window in Windows and Linux ?  In Ubuntu I followed the advice in
this article:

http://ekith.com/index.php?option=com_content&task=view&id=10181

but found that System/Preferences/Keyboard Shortcuts does not allow you to
define your own action.  I created launchers for my Python scripts but
clicking on them seemed to have no effect.

I guess my expectation should be the answer is no, in which case I'd be
happy just to find out if it's possible to create key-bindings in Xemacs to
call a Python program.  I have a feeling the answer to this query is no as
well, in which case my next step is to port the following to elisp:

def output_current_datetime_in_my_desired_format():
   import datetime
   print datetime.datetime.now().strftime("%d%b%Y%a %I:%M%p").upper()

def output_current_time_in_my_desired_format():
   import datetime
   print 
datetime.datetime.now().strftime("%I:%M%p").upper().rjust(20)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] adding a new folder to Python's importable modules search path

2007-11-25 Thread tpc247
Dear fellow Python enthusiasts,

I trust your Thanksgiving holiday has been a relaxing one.  A quick question
for you: I have a script that attempts to import my_module from a folder
that is not in Python's importable modules search path.  In my script, that
I run from the command line, I have the following lines:

import os
import sys

PATH_TO_MODULE = os.path.join('path', 'to', 'my', 'module')
sys.append(PATH_TO_MODULE)

import my_module

When I attempt to run the script, I get the following error message:

ImportError: No module named my_module

In Python IDLE when I perform the aforementioned steps in the order
indicated I can import my_module successfully.  My assumption is Python's
importable modules search path is in sys.path.  In both cases I identify the
path to the folder containing my module, I append said path to sys.path, and
when I attempt to import my_module by either running from the command line
or in IDLE, I get different behavior.  I read the information here again:

http://docs.python.org/tut/node8.html

so I believe I am doing everything correctly.  Am I doing something wrong ?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding a new folder to Python's importable modules search path

2007-11-25 Thread tpc247
On 11/25/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
>
>
> Should be sys.path.append(...)
>
> Kent



yes, I'm sorry, in my posting I did have a  typographical error, but my code
has the following seemingly correct lines:

sys.path.append(PATH_TO_MODULE)
print "Path added: ", PATH_TO_MODULE

so when I run my script from the command line, the folder does seem to be
added to Python's importable modules search path.  When I attempt to import
my_module I get the error:

ImportError: No module named my_module
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding a new folder to Python's importable modules search path

2007-11-26 Thread tpc247
hey guys, thanks a lot for your insight (or lack thereof) which convinced me
to try further investigation on what I might have left out.  One significant
point of correction: for purposes of simplification, I neglected to include
for your review the fact that when I attempted to add my path to Python's
importable modules search path, I did the following:


import os
import sys

folder_1 = os.path.join('x', 'y', 'z', 'w', 's')
folder_2 = os.path.join('x', 'y', 'z', 't', 'm', 'n', 'a', 'b', 'c', 'd')
folders = [folder_1, folder_2]

for a_path in folders:
sys.path.append(os.path.join("F://", a_path) + os.sep)

import My_Module

ImportError: No module named TableParse

sys.path.append(os.path.join("F://", folder_1) + os.sep)
sys.path.append(os.path.join("F://", folder_2) + os.sep)

import My_Module

ImportError: No module named TableParse


apparently the interpreter does not like the os.sep at the end of the search
path.  Once I removed it, everything was gravy.

On 11/26/07, Dave Kuhlman <[EMAIL PROTECTED]> wrote:
>
> On Sun, Nov 25, 2007 at 11:14:47PM -0800, Jeff Younker wrote:
> >
> > > so when I run my script from the command line, the folder does seem
> > > to be added to Python's importable modules search path.  When I
> > > attempt to import my_module I get the error:
> > >
> > > ImportError: No module named my_module
> >
> > Do your module directories have an __init__.py file
> > in them?
>
> Actually, you do not need an __init__.py file in directories that
> are immediately in sys.path.  You *do* need that __init__.py file
> in sub-directories (which you access via dot notation).  See:
>
> http://docs.python.org/ref/import.html  (and search for __init__)
>
> Dave
>
> --
> Dave Kuhlman
> http://www.rexx.com/~dkuhlman
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding a new folder to Python's importable modules search path

2007-11-26 Thread tpc247
and for purposes of continuity TableParse should be replaced with My_Module
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How do I make a variable that refers to an object have the same label as the object's name ?

2006-10-05 Thread tpc247
question for the Python crowd:when creating a series of objects, where each object represents a field from a submitted html form, how do I make variables that reference the objects be the same as the names of the respective objects ?
For example, I have a class called Datum:class Datum:    def __init__(self, key, value, required=None, label=None):    self.key = key    self.value = value    self.required = required
    self.label = labeland a dictionary of submitted values:some_dict = {'applicant_full_name':'John Smith', 'applicant_address_line_1':'100 Main Street', 'applicant_city':'Anytown', 'applicant_state':'WY', 'applicant_postal_code':'5', 'country':'US', '
applicant_email':'[EMAIL PROTECTED]', 'applicant_telephone':'555 555 '} and I created a list of objects like so:some_list = []for key, value in some_dict.items():
    some_datum = Datum(key, value)    some_list.append(some_datum)so now I have a list of Datum instances called some_list, and I would like to make it so I can refer to each respective Datum instance by its 
Datum.key, e.g., applicant_full_name would refer to the Datum instance with key 'applicant_full_name' and applicant_full_name.value would give me "John Smith."  I tried:for x in some_list:    some_string = "%s = %s"  % (
x.key, x)    eval(some_string)and got:Traceback (most recent call last):  File "", line 4, in -toplevel-    eval(some_string)  File "", line 1
    applicant_state = <__main__.Datum instance at 0x009745F8>    ^SyntaxError: invalid syntaxAm I doing something wrong ?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears

2006-10-06 Thread tpc247
hi all, I would like to create a class that specializes Python
dictionary.  I would like an instance of this class to store
objects representing html form data, and I would like to have an
instance of this Data_Set class be able to use the Python dictionary
method pop to remove objects as I see fit.  I defined the
following:

class Data_Set(dict):
    def __init__(self, dict_of_datum_objects, required=None):
    self.keys = dict_of_datum_objects.keys
    self.values = dict_of_datum_objects.values
    self.required = required

For some reason, whenever I create an instance of this class with data,
all I get is an empty dictionary.  As soon as I redefine my class
to no longer inherit from Python dictionary, then I get expected
behavior, but now I don't have benefit of Python dictionary methods
such as pop and has_key:

sdso = Data_Set({'full_name':'full_name_obj', 'address_line_1':'address_line_1_obj'})
>>> sdso
{}
>>> class Data_Set:
    def __init__(self, dict_of_datum, required=None):
    self.keys = dict_of_datum.keys
    self.values = dict_of_datum.values
    self.items = dict_of_datum.items
    self.required = required

    
>>> sdso = Data_Set({'full_name':'full_name_obj', 'address_line_1':'address_line_1_obj'})
>>> sdso
<__main__.Data_Set instance at 0x419690ac>
>>> sdso.keys()
['full_name', 'address_line_1']
>>> sdso.pop('full_name')

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    sdso.pop('full_name')
AttributeError: Data_Set instance has no attribute 'pop'

Am I doing something wrong ?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] my first object model, using an interface

2008-07-05 Thread tpc247
Dear fellow Python enthusiasts:

I want to run an idea by you to see if I understand modeling objects
adequately, after reading Alan Gauld's excellent tutorial and two brief
articles about interfaces in Python, here:

 http://www.freenetpages.co.uk/hp/alan.gauld/tutclass.htm

http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html
 http://nedbatchelder.com/text/pythonic-interfaces.html

I am attempting to model the following:
a correspondence school has asked me to help them solve a problem.  When the
school sends a student by mail a package containing several courses, each
course having several pieces of gradable homework, when a specific threshold
of homework completed and submitted by the student is met or exceeded,
another package is sent to the student by mail.  Now, this aforementioned
threshold, i.e., an integer indicating percentage, can vary, and is not just
for the totality of homework in the package, but also for certain courses
with many pieces of homework.  For example, say the school sends student Joe
a package (package_1) containing courses A, B and C_sub1.  A, B & C_sub1
have 10 pieces of gradable homework, and the school wants that we can set a
threshold for the totality of homework for package1, as well as a threshold
for C_sub1 alone.  When the thresholds are met or exceeded, independently,
then we send package_2 and C_sub2, respectively.  I envisioned a nascent
object model and noted the following observations:

- a Watchable interface that, when implemented, signifies that the
implementing object has a threshold and associated package.
- a Package class, that can be seen as a container for courses and/or one
part of a course
- a Course class, that can be seen as a container for gradable homework
- a Homework class, that has a flag to indicated whether it has been
received by the school
- most Packages are Watchable (except the last Package object), and only one
or two Courses in a Package need to be Watchable

Two questions:
1) Should I create a first-class Watchable interface object, and then have
my Package and Course objects implement it if they need to ?  If I start
with a Watchable interface, do I handle the name-space conflict, i.e.,
Package(object) vs Package(Watchable), by defining a Package class, and a
W_Package class that implements Watchable, and likewise for Course ?
2) am I even thinking the right way about attacking this problem ?  I am
curious what your experience in writing easy to maintain software might tell
you about my nascent object model.

class Watchable(object):
def set_threshold(self, an_int):
raise NotImplemented
def get_threshold(self):
raise NotImplemented
def set_associated_load(self, a_load):
raise NotImplemented
def get_associated_load(self):
raise NotImplemented

class Package(object):
def __init__(self, courses):
self.set_courses(courses)
def set_courses(self, courses):
self.courses = courses
def get_courses(self):
return self.courses

class Course(Watchable):
def __init__(self, name, homework):
self.name = name
self.homework = homework
def get_name(self):
return self.name
def get_homework(self):
return self.homework

class Homework(object):
def __init__(self, name):
self.name = name
self.academically_received = False
def set_academically_received(self):
self.academically_received = True
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor