[Tutor] Trivia program.

2005-02-16 Thread . Sm0kin'_Bull
Hi, I got a problem with this program.


name = raw_input("Hi. What's your name? ")called = name * 5print "\nIf a small child were trying to get your attention, " \ "your name would become:"print called
When i input the name like "John Goodman"

it prints like...

John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman

But i want to print it like...


John Goodman John Goodman John Goodman John Goodman John Goodman

How can I do it?Express yourself instantly with MSN Messenger! MSN Messenger Download today it's FREE!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Re: Basic terminology

2005-02-16 Thread Roel Schroeven
Bill Mill wrote:
 However, where will it be pointing in 16 hours? Well, in 12 hours it
 will be at the one, then four more hours later it will be pointing at
 the five. This can be represented as:
 
 1 + (16 % 12) = 1 + 4 = 5

Correcter is

(1 + 16) % 12 = 17 % 12 = 5

 In general, the hour at some point in the future will be:
 
 (start time) + (hours in the future % 12)

(start time + hours in the future) % 12

The difference can be seen in a small example: suppose it is 10 o'clock,
and you want to know what it will be in 6 hours.

Your formula gives

10 + (6 % 12) = 10 + 6 = 16

which is not correct (unless dealing with 24-hour systems of course, but
that's not the case here)

Correct is:

(10 + 6) % 12 = 16 % 12 = 4

(In 24-hour systems, just replace 12 with 24)

-- 
Codito ergo sum
Roel Schroeven

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trivia program.

2005-02-16 Thread Pierre Barbier de Reuille
Mmmhh ... one very simple way would be to replace your first line by :
name = raw_input(Hi. What's your name? ) +   
But if you want to keep the name as it is, I bet the best way is to 
replace your second line by :

called =   .join([ name for i in xrange(5) ])
The advantage of this second method is theis added only *between* 
the names, and not after ...

Pierre
. Sm0kin'_Bull a écrit :
Hi, I got a problem with this program.
 
 
name = raw_input(Hi. What's your name? )
called = name * 5
print \nIf a small child were trying to get your attention,  \
   your name would become:
print called
When i input the name like John Goodman
 
it prints like...
 
John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman
 
But i want to print it like...
 
John Goodman  John Goodman  John Goodman  John Goodman  John Goodman
 
How can I do it?


Express yourself instantly with MSN Messenger! MSN Messenger 
http://g.msn.com/8HMBEN/2728??PS=47575 Download today it's FREE!


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trivia program.

2005-02-16 Thread Max Noel
On Feb 16, 2005, at 10:26, . Sm0kin'_Bull wrote:
it prints like...
 
John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman
 
But i want to print it like...
 
John Goodman  John Goodman  John Goodman  John Goodman  John Goodman
 
How can I do it?
Try replacing the called = name * 5 line with:
if not name.endswith(' '):
called = ((name + ' ') * 5).strip()
else:
called = (name * 5).strip()
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
Look at you hacker... A pathetic creature of meat and bone, panting 
and sweating as you run through my corridors... How can you challenge a 
perfect, immortal machine?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trivia program.

2005-02-16 Thread Liam Clarke
Or 
 name = raw_input(Hi. What's your name? )
called = %s  % name 


On Wed, 16 Feb 2005 11:46:09 +0100, Pierre Barbier de Reuille
[EMAIL PROTECTED] wrote:
 Mmmhh ... one very simple way would be to replace your first line by :
 
 name = raw_input(Hi. What's your name? ) +   
 
 But if you want to keep the name as it is, I bet the best way is to
 replace your second line by :
 
 called =   .join([ name for i in xrange(5) ])
 
 The advantage of this second method is theis added only *between*
 the names, and not after ...
 
 Pierre
 
 . Sm0kin'_Bull a écrit :
  Hi, I got a problem with this program.
 
 
  name = raw_input(Hi. What's your name? )
  called = name * 5
  print \nIf a small child were trying to get your attention,  \
 your name would become:
  print called
  When i input the name like John Goodman
 
  it prints like...
 
  John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman
 
  But i want to print it like...
 
  John Goodman  John Goodman  John Goodman  John Goodman  John Goodman
 
  How can I do it?
 
  
  Express yourself instantly with MSN Messenger! MSN Messenger
  http://g.msn.com/8HMBEN/2728??PS=47575 Download today it's FREE!
 
 
  
 
  ___
  Tutor maillist  -  Tutor@python.org
  http://mail.python.org/mailman/listinfo/tutor
 
 --
 Pierre Barbier de Reuille
 
 INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
 Botanique et Bio-informatique de l'Architecture des Plantes
 TA40/PSII, Boulevard de la Lironde
 34398 MONTPELLIER CEDEX 5, France
 
 tel   : (33) 4 67 61 65 77fax   : (33) 4 67 61 56 68
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 


-- 
'There is only one basic human right, and that is to do as you damn well please.
And with it comes the only basic human duty, to take the consequences.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary dispatch for object instance attributes question

2005-02-16 Thread Kent Johnson
Brian van den Broek wrote:
My Node class defines a _parse method which separates out the node 
header, and sends those lines to a _parse_metadata method. This is where 
the elif chain occurs -- each line of the metadata starts with a tag 
like dt= and I need to recognize each tag and set the appropriate Node 
object attribute, such as .document_type. (I do not want to rely on the 
unhelpful names for the tags in the file format, preferring more 
self-documenting attribute names.)

I've come up with *a* way to use a dictionary dispatch, but I'll wager a 
great deal it isn't the *best* way.

Here is a minimal illustration of what I have come up with:
code
class A:
def __init__(self):
self.something = None
self.something_else = None
self.still_another_thing = None

def update(self, data):

for key in metadata_dict:
if data.startswith(key):
exec('''self.%s = %s''' %(metadata_dict[key],
 data[len(key):]))
# triple quotes as there may be quotes in metadata
# values
break
metadata_dict = {'something_tag=': 'something',
 '2nd_tag=': 'something_else',
 'last=': 'still_another_thing'}
a = A()
print a.still_another_thing
a.update('last=the metadata value for the last= metadata tag')
print a.still_another_thing
/code
output
 
None
the metadata value for the last= metadata tag
/output
So, it works. Yay :-)
But, should I be doing it another way?
Another way to do this is to use dispatch methods. If you have extra processing to do for each tag, 
this might be a good way to go.

I'm going to assume that your data lines have the form 'tag=data'. Then your Node class might have 
methods that look like this:

class Node:
  ...
  def parse_metadata(self, line):
tag, data = line.split('=', 1)
try:
  handler = getattr(self, 'handle_' + tag)
except AttributeError:
  print 'Unexpected tag:', tag, data
else:
  handler(data)
  def handle_something_tag(self, data):
self.something = int(data) # for example
  def handle_last(self, data):
try:
  self.another_thing.append(data) # attribute is a list
except AttributeError:
  self.another_thing = [data]
and so on. This organization avoids any if / else chain and puts all the processing for each tag in 
a single place.

BTW the try / except / else idiom is used here to avoid catching unexpected 
exceptions. The naive
way to write it would be
try:
  handler = getattr(self, 'handle_' + tag)
  handler(data)
except AttributeError:
  print 'Unexpected tag:', tag, data
The problem with this is that if handler() raise AttributeError you will get an unhelpful error 
message and no stack trace. Putting the call to handler() in an else clause puts it out of the scope 
of the try / except but it will still be executed only if the getattr succeeds.

Also, I know the general security concerns about things like exec. They 
make me nervous in using it, even though I am (as yet) the sole user. Am 
I right in thinking that the constrained way I am using it here protects 
me? My code uses most of the attributes as a simple storage container 
for later rewriting of the file, but in a few cases they enter into 
(safe seeming) conditionals like:

if 'text' == self.document_type:
   self.do_text_stuff()
if 'RTF' == self.document_type:
   self.do_RTF_stuff()
Conditionals on a 'type' flag are a code smell that suggests using subclasses. Maybe you should have 
a TextNode class and an RtfNode class. Then the above becomes just
  self.do_stuff()

and TextNode and RtfNode each have the appropriate implementations of 
do_stuff().
I'm not saying this is the right choice for you, just something you might 
consider.
Kent
Thanks and best to all,
Brian vdB
___
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] best way to scrape html

2005-02-16 Thread Kent Johnson
You might find these threads on comp.lang.python interesting:
http://tinyurl.com/5zmpn
http://tinyurl.com/6mxmb
Peter Kim wrote:
Which method is best and most pythonic to scrape text data with
minimal formatting?
I'm trying to read a large html file and strip out most of the markup,
but leaving the simple formatting like p, b, and i.  For example:
p class=BodyText style=MARGIN: 0in 0in 12ptfont face=Times New
Romanb style=font-weight: normalspan lang=EN-GB
style=FONT-SIZE: 12ptTrigger:/span/bspan lang=EN-GB
style=FONT-SIZE: 12ptspan style=spacerun: yes#160;/span
Debate on budget in Feb-Mar. New moves to cut medical costs by better
technology./span/font/p
I want to change the above to:
pbTrigger:/b Debate on budget in Feb-Mar.  New moves to
cutmedical costs by better technology./p
Since I wanted some practice in regex, I started with something like this:
pattern = (?:)(.+?)(?: ?.*?)(.*?)(/\1)
result = re.compile(pattern, re.IGNORECASE | re.VERBOSE |
re.DOTALL).findall(html)
But it's getting messy real fast and somehow the non-greedy parts
don't seem to work as intended.  Also I realized that the html file is
going to be 10,000+ lines, so I wonder if regex can be used for large
strings.
So I'm thinking of using sgmllib.py (as in the Dive into Python
example).  Is this where I should be using libxml2.py?  As you can
tell this is my first foray into both parsing and regex so advice in
terms of best practice would be very helpful.
Thanks,
Peter Kim
___
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] dictionary dispatch for object instance attributes question

2005-02-16 Thread Kent Johnson
Kent Johnson wrote:
Another way to do this is to use dispatch methods. If you have extra 
processing to do for each tag, this might be a good way to go.

I'm going to assume that your data lines have the form 'tag=data'. Then 
your Node class might have methods that look like this:

class Node:
  ...
  def parse_metadata(self, line):
tag, data = line.split('=', 1)
try:
  handler = getattr(self, 'handle_' + tag)
except AttributeError:
  print 'Unexpected tag:', tag, data
else:
  handler(data)
  def handle_something_tag(self, data):
self.something = int(data) # for example
  def handle_last(self, data):
try:
  self.another_thing.append(data) # attribute is a list
except AttributeError:
  self.another_thing = [data]
and so on. This organization avoids any if / else chain and puts all the 
processing for each tag in a single place.
One more idea. If you have 20 different tags but only four different ways of processing them, maybe 
you want to use a dict that maps from the tag name to a tuple of (attribute name, processing 
method). With this approach you need only four handler methods instead of 20. It would look like this:

metadata_dict = {
  'something_tag' : ( 'something', self.handle_int ),
  'last' : ( 'another_thing', self.handle_list ),
}
def parse_metadata(self, line):
  tag, data = line.split('=', 1)
  try:
attr_name, handler = metadata_dict[tag]
  except AttributeError:
print 'Unexpected tag:', tag, data
  else:
handler(attr_name, data)
def handle_int(self, attr_name, data):
  setattr(self, attr_name, int(data))
def handle_list(self, attr_name, data):
  l = getattr(self, attr_name, [])
  l.append(data)
  setattr(self, attr_name, l)
I-have-to-stop-replying-to-my-own-posts-ly yours,
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Queued threads

2005-02-16 Thread Jeremy Jones
Not to beat a dead horse, but
Liam Clarke wrote:
Oops, you probably want to do this then- 

for i in range( 0, 3 ):
oThread = Thread( target=mainFunction ).start()
 

Thread.start() looks like it returns None.
#
In [23]: from threading import Thread
In [24]: import time
In [25]: def foo():
  : print doing...
  : time.sleep(15)
  : print done
  :
In [26]: t = Thread(target=foo).start()
doing...
In [27]: print t
None
In [28]: done
In [28]: print t
None
In [29]: t = Thread(target=foo)
In [30]: t.start()
doing...
In [31]: t.isAlive()
Out[31]: True
In [32]: done
In [32]: t.isAlive()
Out[32]: False
#
So, checking the return of Thread.start() doesn't seem like it would do 
what you think it would do.  You probably want to get the thread object 
and check that directly with isAlive().  Oh, and if you spawn a bunch of 
threads at once and you want to wait until the all complete before doing 
something else, do something like this:

#
#create a list to contain the threads
thread_list = []
for i in range(10):
   t = Thread(target=foo)
   print creating thread, t
   #put each thread in the list
   thread_list.append(t)
#iterate over thread list and start each thread
for t in thread_list:
   print starting thread, t
   t.start()
#iterate over thread list and wait for each thread
for t in thread_list:
   print waiting for thread, t
   while 1:
   if not t.isAlive():
   break
   time.sleep(.2)
#
It'll give you output something like this:
#
creating thread Thread(Thread-35, initial)
creating thread Thread(Thread-36, initial)
creating thread Thread(Thread-37, initial)
creating thread Thread(Thread-38, initial)
creating thread Thread(Thread-39, initial)
creating thread Thread(Thread-40, initial)
creating thread Thread(Thread-41, initial)
creating thread Thread(Thread-42, initial)
creating thread Thread(Thread-43, initial)
creating thread Thread(Thread-44, initial)
starting thread Thread(Thread-35, initial)
starting thread Thread(Thread-36, initial)
starting thread Thread(Thread-37, initial)
starting thread Thread(Thread-38, initial)
doing...
starting thread Thread(Thread-39, initial)
doing...
doing...
starting thread Thread(Thread-40, initial)
doing...
starting thread doing...
Thread(Thread-41, initial)
doing...
starting thread Thread(Thread-42, initial)
starting thread Thread(Thread-43, initial)
starting thread Thread(Thread-44, initial)
doing...
doing...
doing...
waiting for thread Thread(Thread-35, started)
doing...
done
done
done
done
done
done
waiting for thread Thread(Thread-36, stopped)
waiting for thread Thread(Thread-37, stopped)
waiting for thread done
done
done
done
Thread(Thread-38, stopped)
waiting for thread Thread(Thread-39, stopped)
waiting for thread Thread(Thread-40, stopped)
waiting for thread Thread(Thread-41, stopped)
waiting for thread Thread(Thread-42, stopped)
waiting for thread Thread(Thread-43, stopped)
waiting for thread Thread(Thread-44, stopped)
#
But in this situation, I totally agree with Max.  You don't need threads 
for this.  Just use os.system.  You could use one of the popens (or the 
new subprocess module - never used that one myself), but os.system 
blocks until the called program exits.

   while oThread: 
print 'sleeping 3 seconds'
time.sleep( 3 )

A if condition generally has an implicit else: pass clause as I
think of it, so it will just keep reiterating if the condition isn't
met.
 

Jeremy Joens
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with variables

2005-02-16 Thread . Sm0kin'_Bull

wrote this, It's a bit lame thoughI = "Allen"me = "Allen"my = "Allen's"print \"""%s woke up early in the morning. But, it was unusal by %s. %s pillowwas with %s. %s didn't want to wake up But, %s tried my best and woke up.it was so amazing!""" % (I,me,my,me,I,I)raw_input("\n\\t\t\t- The End -")But it looks like this...Allen woke up early in the morning. But, it was unusal by Allen. Allen's pillowwas with Allen. Allen didn't want to wake up But, Allen tried my best and woke up.it was so amazing - The End -
the problem is about lining
I want it to print like this...
Allen woke up early in the morning. But, it was unusal by Allen.
Allen's pillow was with Allen. Allen didn't want to wake up But, Allen
tried my best and woke up. it was so amazing
FREE pop-up blocking with the new MSN Toolbar MSN Toolbar Get it now!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problems in making calulating program.

2005-02-16 Thread . Sm0kin'_Bull
I wrote this to add 2 numbers...print "Please input data"number1 = int(raw_input(" "))number2 = int(raw_input("+ "))total = number1 + number2print totalraw_input("")I want to make output like this...1 + 1 = 2But, actually... it looks like this...1+ 12
Express yourself instantly with MSN Messenger! MSN Messenger Download today it's FREE!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem with variables

2005-02-16 Thread Jeremy Jones




. Sm0kin'_Bull wrote:

  
  wrote this, It's a bit lame though
  
I = "Allen"
me = "Allen"
my = "Allen's"
  
print \
"""
%s woke up early in the morning. But, it was unusal by %s. %s pillow
was with %s. %s didn't want to wake up But, %s tried my best and woke
up.
it was so amazing!""" % (I,me,my,me,I,I)
  
raw_input("\n\\t\t\t- The End -")
  
But it looks like this...
  
Allen woke up early in the morning. But, it was unusal by Allen. 
Allen's pillow
was with Allen. Allen didn't want to wake up But, Allen tried my best
and woke up.
it was so amazing
  
 - The End -
  
  
  
  the problem is about lining
  
  I want it to print like this...
  
  Allen woke up early in the morning. But, it was unusal by Allen.
Allen's pillow was with Allen. Allen didn't want to wake up But, Allen
tried my best and woke up. it was so amazing
  
  
  
  


This is what I got:


In [45]: I = "Allen"

In [46]: me = "Allen"

In [47]: my = "Allen's"

In [48]:

In [48]: print \
 : """
 : %s woke up early in the morning. But, it was unusal by %s. %s
pillow
 : was with %s. %s didn't want to wake up But, %s tried my best
and woke up.
 : it was so amazing!""" % (I,me,my,me,I,I)

Allen woke up early in the morning. But, it was unusal by Allen.
Allen's pillow
was with Allen. Allen didn't want to wake up But, Allen tried my best
and woke up.
it was so amazing!


It looks like it should. If you want it to show up exactly like posted
at the end, you need something more like this:


In [50]: print \
 : """
 : %s woke up early in the morning. But, it was unusal by %s.
 : %s pillow was with %s. %s didn't want to wake up But, %s
 : tried my best and woke up. it was so amazing!""" %
(I,me,my,me,I,I)

Allen woke up early in the morning. But, it was unusal by Allen.
Allen's pillow was with Allen. Allen didn't want to wake up But, Allen
tried my best and woke up. it was so amazing!
###

Jeremy Jones



  
  
  
  
  FREE pop-up blocking with the new MSN Toolbar MSN Toolbar
Get it now!
  

___
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] Re: Basic terminology

2005-02-16 Thread Bill Mill
On Wed, 16 Feb 2005 11:34:55 +0100, Roel Schroeven
[EMAIL PROTECTED] wrote:
 Bill Mill wrote:
  However, where will it be pointing in 16 hours? Well, in 12 hours it
  will be at the one, then four more hours later it will be pointing at
  the five. This can be represented as:
 
  1 + (16 % 12) = 1 + 4 = 5
 
 Correcter is
 
 (1 + 16) % 12 = 17 % 12 = 5

d'oh! thanks for the correction.

 
  In general, the hour at some point in the future will be:
 
  (start time) + (hours in the future % 12)
 
 (start time + hours in the future) % 12
 

Peace
Bill Mill
bill.mill at gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Case acceptance using raw_input

2005-02-16 Thread Bob Gailer
At 11:40 PM 2/15/2005, Alan Gauld wrote:
 Is there a better way for raw_input to accept both caps and lower
case letters than:
 def aFunction():
action = raw_input(Perform an action?(y,n): )
action = raw_input(Perform an action?(y,n): ).upper()
if action == 'y' or action == 'Y':
if action == 'Y':
anotherFunction()
etc.
Bob Gailer
mailto:[EMAIL PROTECTED]
303 442 2625 home
720 938 2625 cell 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary dispatch for object instance attributes question

2005-02-16 Thread Brian van den Broek
Kent Johnson said unto the world upon 2005-02-16 05:58:
Brian van den Broek wrote:
SNIP Kent's useful explanation of how to use handlers
Also, I know the general security concerns about things like exec. 
They make me nervous in using it, even though I am (as yet) the sole 
user. Am I right in thinking that the constrained way I am using it 
here protects me? My code uses most of the attributes as a simple 
storage container for later rewriting of the file, but in a few cases 
they enter into (safe seeming) conditionals like:

if 'text' == self.document_type:
   self.do_text_stuff()
if 'RTF' == self.document_type:
   self.do_RTF_stuff()

Conditionals on a 'type' flag are a code smell that suggests using 
subclasses. Maybe you should have a TextNode class and an RtfNode class. 
Then the above becomes just
  self.do_stuff()

and TextNode and RtfNode each have the appropriate implementations of 
do_stuff().

I'm not saying this is the right choice for you, just something you 
might consider.

Kent
Hi Kent,
thanks for the snipped discussion on handlers -- very useful.
As for the code smell thing, I have a follow-up question. I now get 
the point of the type-based conditional being a smell for classes. (I 
get it due to a previous thread that an over-enthusiastic inbox purge 
prevents me from citing with certainty, but I think it was Bill and 
Alan who clarified it for me.)

My problem is that I've got a lot of code which was written before I 
got that point and my code doesn't yet actually do much. (I do have 
working code for parsing my original source files and storing all of 
their metadata, etc., but I haven't yet got working code for doing the 
manipulating the data in the ways I want.)

I had been thinking better to get everything working and then 
refactor. Is that an unsound approach? My worry about refactoring now 
is that I feel like I am rearranging deck-chairs when I should be 
worried about getting the ship to float :-)

Thanks and best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary dispatch for object instance attributes question

2005-02-16 Thread Kent Johnson
Brian van den Broek wrote:
As for the code smell thing, I have a follow-up question. I now get the 
point of the type-based conditional being a smell for classes. (I get it 
due to a previous thread that an over-enthusiastic inbox purge prevents 
me from citing with certainty, but I think it was Bill and Alan who 
clarified it for me.)

My problem is that I've got a lot of code which was written before I got 
that point and my code doesn't yet actually do much. (I do have working 
code for parsing my original source files and storing all of their 
metadata, etc., but I haven't yet got working code for doing the 
manipulating the data in the ways I want.)

I had been thinking better to get everything working and then refactor. 
Is that an unsound approach? My worry about refactoring now is that I 
feel like I am rearranging deck-chairs when I should be worried about 
getting the ship to float :-)
It's a hard question because it really comes down to programming style and 
judgement.
I like to work in a very incremental style - design a little, code a little, test a little, repeat 
as needed. I believe in 'Refactor Mercilessly' - another XP slogan. I have many years experience and 
a well-developed opinion of what is good design and bad design.

One consequence of this style is, I usually have working code and tests to go with it. It may not do 
very much, but it works.

So for me, if I smell something, and think that refactoring into subclasses - or some other change - 
is the best design for the problem as I understand it, I will probably do the refactoring. It's not 
going to be easier tomorrow :-) If it just smells a little, or the refactoring is major, I might 
think about how to get rid of the smell but put it off until I'm pretty sure it is a good idea.

I don't think of this as rearranging the deck chairs - it's more like building the right foundation. 
Clean, expressive, well-designed code is a pleasure to work with.

For you, it's probably not so cut-and-dried. If you don't have the experience to judge how bad a 
smell is, or to think through the possibilities so clearly, it's harder to know how to proceed. If 
you are in part dabbling with OOP design to learn about it, maybe you want to put off some changes 
until the code is working; then you could make the change and do a comparison and see which one 
feels cleaner to you.

I hope this helps at least a little :-)
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Queued threads

2005-02-16 Thread Jeff Shannon
On Wed, 16 Feb 2005 16:50:07 +1300, Liam Clarke [EMAIL PROTECTED] wrote:
 Oops, you probably want to do this then-
 
 for i in range( 0, 3 ):
  oThread = Thread( target=mainFunction ).start()
 
 while oThread:
  print 'sleeping 3 seconds'
  time.sleep( 3 )

Probably not.  Note that, since oThread's value is not changed in the
body of this while loop, you will either never execute the body (if
oThread is false) or execute it infintely many times (if oThread is
true).  I doubt that's the desired behavior. ;)

In this case, since Thread.start() apparently always returns None, the
while loop is effectively a no-op.  However, if it *did* get
triggered, it would do so immediately after the first thread [which
returned a true value from start()] was started -- preventing later
threads from being started because the main program is stuck in this
endless loop.

You could perhaps rewrite the whole thing like this:

.for i in range(3):
.mythread = Thread(target=mainFunction)
.mythread.start()
.while mythread.isAlive():
.print sleeping 3 seconds [main thread]
.time.sleep(3)

Though as others have said, if you're not starting the second thread
until the first is finished, then you might as well just make it
explicitly sequental and not bother with threads:

.for i in range(3):
.mainFunction()

If you actually want the threads to process concurrently, and simply
wait until all of them are done, you could do this:

.threadlist = []
.for i in range (3):
.mythread = Thread(target=mainFunction)
.mythread.start()
.threadlist.append(mythread)
.for thread in threadlist:
.thread.join()

The join() method will wait until that thread is finished, and then
return.  If the thread is already finished when it's called, it
returns immediately.

Jeff Shannon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary dispatch for object instance attributes question

2005-02-16 Thread Jeff Shannon
On Tue, 15 Feb 2005 23:48:31 -0500, Brian van den Broek
[EMAIL PROTECTED] wrote:
 Jeff Shannon said unto the world upon 2005-02-15 21:20:
  On Tue, 15 Feb 2005 17:19:37 -0500, Brian van den Broek
  [EMAIL PROTECTED] wrote:
 
  For starters, I've made metadata a class attribute rather than an
  unconnected dictionary.  This seems conceptually nicer to me.
 
 The problem is that my Node instance live in a TP_file class instance,
 and the way my code is now, the TP_file instance also needs to see the
 metadata dict. There are a few tags, which if present in any Node of
 the file make me want to treat the entire file a bit differently. (Of
 course, here is the place where my novice-designer status is most
 likely to be bitting me.) So, that's why I have it as a module level
 object, rather than within a class. (I do, however, see your point
 about it being neater.)

Okay, that makes sense.  You have two different classes (the TP_file
class and the Node class) that need access to the same information, so
yes, having it at the module level lets them share it more
effectively.  (Alternately, since it sounds like the TP_file class is
where all of the Node instances are created, you *could* decide that
the metadata belongs as part of the TP_file, which would then actively
share it with Node... but what you've got sounds like a very
reasonable plan, so at this point I wouldn't worry about it.)

  In addition, update() can now modify several attributes at once, at
  the cost of a bit of extra parsing up front.
 
 The metadata all occurs one element to a line in my original file.
 [...] Maybe I'm still missing a better way, but as I am processing
 line by line, each line with one element, I don't see how to use this
 cool looking multiple elements at once approach. 

Yes, if you know that you will only have one header per line, then
it's reasonable to process them one line at a time.  You could
alternatively have the TP_file gather all the header lines for a given
node into a list, and then process that list to create the Node
instance, but given the specifics of your case you probably wouldn't
gain anything over your current approach by doing so.

This is what makes programming so interesting -- there's so many
different choices possible, and which one is best depends on a large
number of factors.  When writing a program for some task, the best
design for a particular set of circumstances may be completely
different than the best design for a somewhat different particular set
of circumstances -- and the best design for general usage is probably
an altogether different thing still.

Good luck!

Jeff Shannon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: ****SPAM(11.2)**** [Tutor] Larger program organization

2005-02-16 Thread Terry Carroll
On Fri, 11 Feb 2005, Bob Gailer wrote:

 Whenever you find yourself writing an if statement ask whether this
 would be better handled by subclasses. Whenever you find yourself about
 to write a global statement, consider making the variables properties of
 a class.

Bob -- 

Brian already asked for an explanation of your first statement, and I 
found the ensuing discussion very instructive.

Can you explain the second?  As an aesthetic point, I hate globals, and 
I'd love a discussion with some examples of using class variables as a way 
of avoiding this.

Terry

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help needed with script to batch-create shapefiles

2005-02-16 Thread Chris Bromley
Dear all, 

I have several thousand files in dBaseIV format that I need to convert to 
shapefiles for use in ArcGIS. I've written a script (see below) to automate 
this process but thus far have been unable to get it to work. I suspect that 
there's a simple reason for this, but I'm a complete novice with Python and 
have been unable to find it.

Any help would be greatly appreciated!

Regards, 

Chris Bromley 


##Script Name: dBase Table to Shapefile
##Description: Converts dBase files to shapefiles
##Created By: Chris Bromley.
##Date: 16/02/2005

# Import system modules
import sys, string, os, win32com.client

# Create the Geoprocessor object
gp = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1)

try:
# Load required toolboxes...
gp.AddToolbox(C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion 
Tools.tbx)
gp.AddToolbox(C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management 
Tools.tbx)

#Define  create variables to contain the source files and output file 
location paths
gp.workspace = 
C:\PhD\ElwhaRiverProject\Physical_modelling\Model_Data_Corrected\Tester3\One
out_workspace = 
C:\PhD\ElwhaRiverProject\Physical_modelling\Model_Data_Corrected\Tester3

# Get a list of the dBase tables in the workspace
fcs = gp.ListTables(*,dBase)
# Loop through the list of feature classes
fcs.reset()
fc = fcs.next()

while fc:
# Set the output filename for each output to be the same as the input 
filename
output = out_workspace + fc
# Process: Make XY Event Layer...
gp.MakeXYEventLayer_management(fc, x, y, output, )
# Process: Feature Class To Shapefile (multiple)...
gp.FeatureClassToShapefile_conversion(output, out_workspace, )
fc = fcs.next()

except:
gp.AddMessage(gp.GetMessages(2))
print gp.GetMessages(2)



This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary dispatch for object instance attributes question

2005-02-16 Thread Brian van den Broek
Kent Johnson said unto the world upon 2005-02-16 15:02:
Brian van den Broek wrote:
SNIP
I had been thinking better to get everything working and then 
refactor. Is that an unsound approach? My worry about refactoring now 
is that I feel like I am rearranging deck-chairs when I should be 
worried about getting the ship to float :-)
It's a hard question because it really comes down to programming style 
and judgement.

I like to work in a very incremental style - design a little, code a 
little, test a little, repeat as needed. I believe in 'Refactor 
Mercilessly' - another XP slogan. I have many years experience and a 
well-developed opinion of what is good design and bad design.

One consequence of this style is, I usually have working code and tests 
to go with it. It may not do very much, but it works.

So for me, if I smell something, and think that refactoring into 
subclasses - or some other change - is the best design for the problem 
as I understand it, I will probably do the refactoring. It's not going 
to be easier tomorrow :-) If it just smells a little, or the refactoring 
is major, I might think about how to get rid of the smell but put it off 
until I'm pretty sure it is a good idea.

I don't think of this as rearranging the deck chairs - it's more like 
building the right foundation. Clean, expressive, well-designed code is 
a pleasure to work with.

For you, it's probably not so cut-and-dried. If you don't have the 
experience to judge how bad a smell is, or to think through the 
possibilities so clearly, it's harder to know how to proceed. If you are 
in part dabbling with OOP design to learn about it, maybe you want to 
put off some changes until the code is working; then you could make the 
change and do a comparison and see which one feels cleaner to you.

I hope this helps at least a little :-)
Kent
Hi Kent,
I see my `strike that' msg. didn't get through in time, to save you 
from the reply. But, from the selfish perspective, I'm glad enough 
about that; the above does indeed help more than a little.

I get, in the abstract at least, how Test Driven Development would 
make these refactorings much easier to do with confidence. (Somewhere 
near half the point, isn't it?) The goal of my current project, beyond 
the given of having useful code, is to write a medium sized project in 
OOP. At the outset, I felt I had to choose between getting a handle on 
OOP or TDD. I felt I could only tackle one new paradigm at a time. I 
went with OOP as I didn't want to spend the effort of getting 
procedural code down using TDD and then have to redo it in OOP. But, 
not having test does make the refactoring more scary than I imagine it 
would be tests in hand.

And I would have had the need to redo it, I think. The file format I 
am working with is from an application I've been using as a 
PIM/Knowledge manager for several years. So, I've got tons of data and 
tons of plans. I'm not certain if the term is the right one, but I'm 
thinking of the code I am working on as a base toolset or `framework' 
for all the other things I want to do with the files of that format. 
Thus, subclassing and other OOP techniques are sure to be important 
for those plans.

But, I think you hit it right on the head -- my inexperience with OOP 
doesn't provide me with any metric for judgement about these things. 
Browsing through things like Fowler, Beck, Brant,  Opdyke's 
_Refactoring_, while fun, doesn't help much without my having 
struggled with my own OOP code first. Hey, yesterday I proved that 
having read about setattr numerous times is no guarantee I'll remember 
it the first time a use case comes up :-)

Thanks for the continued efforts to help me `get' it. Best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed with script to batch-create shapefiles

2005-02-16 Thread Bill Mill
Chris,


On Wed, 16 Feb 2005 21:37:10 +, Chris Bromley
[EMAIL PROTECTED] wrote:
 Dear all,
 
 I have several thousand files in dBaseIV format that I need to convert to 
 shapefiles for use in ArcGIS. I've written a script (see below) to automate 
 this process but thus far have been unable to get it to work. I suspect that 
 there's a simple reason for this, but I'm a complete novice with Python and 
 have been unable to find it.
 
 Any help would be greatly appreciated!
 
 Regards,
 
 Chris Bromley
snip script

What you've written translates, in newsgroup-speak, to Will somebody
write this script for me that I need?

Boil your question down into something smaller, and then ask it with
the appropriate information. I suggest reading
http://www.catb.org/~esr/faqs/smart-questions.html .

Peace
Bill Mill
bill.mill at gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary dispatch for object instance attributes question

2005-02-16 Thread Brian van den Broek
Jeff Shannon said unto the world upon 2005-02-16 16:09:
On Tue, 15 Feb 2005 23:48:31 -0500, Brian van den Broek
[EMAIL PROTECTED] wrote:
SNIP some of Jeff's responses to my evaluation of his earlier 
suggestions


Yes, if you know that you will only have one header per line, then
it's reasonable to process them one line at a time.  You could
alternatively have the TP_file gather all the header lines for a given
node into a list, and then process that list to create the Node
instance, but given the specifics of your case you probably wouldn't
gain anything over your current approach by doing so.
This is what makes programming so interesting -- there's so many
different choices possible, and which one is best depends on a large
number of factors.  When writing a program for some task, the best
design for a particular set of circumstances may be completely
different than the best design for a somewhat different particular set
of circumstances -- and the best design for general usage is probably
an altogether different thing still.
Good luck!
Jeff Shannon
Thanks Jeff,
the confirmation that my assessment made sense is very helpful. Due to 
the my lack of experience (as discussed in my response to Kent) I'm 
always uncomfortable rejecting a proposed solution -- is my assessment 
that the solution isn't the best a product of that inexperience, or am 
I on to something? So, thanks for taking the time to `bless' my 
assessment.

Best to all,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: ****SPAM(11.2)**** [Tutor] Larger program organization

2005-02-16 Thread Brian van den Broek
Terry Carroll said unto the world upon 2005-02-16 16:18:
On Fri, 11 Feb 2005, Bob Gailer wrote:

Whenever you find yourself writing an if statement ask whether this
would be better handled by subclasses. Whenever you find yourself about
to write a global statement, consider making the variables properties of
a class.

Bob -- 

Brian already asked for an explanation of your first statement, and I 
found the ensuing discussion very instructive.

Can you explain the second?  As an aesthetic point, I hate globals, and 
I'd love a discussion with some examples of using class variables as a way 
of avoiding this.

Terry

Hi Terry and all,
I'm probably not the best person to explain this, but I've got a use 
case that might help illustrate.

The thing that finally got me to write my first Class statement was a 
procedural program where I had a hard to find bug.

I wrote a debug_report function which would print out an informative 
report about the state of all the objects I suspected were implicated 
in the bug. Then, I put debug_report calls at the suspicious places. 
But, my procedural code had function call chains 4 or 5 links deep, 
and at no level did any of the functions have access to all of the 
objects of interest.

To make it work in purely procedural, I had to either make many 
objects global or litter my functions with passing objects up and down 
as parameters that weren't needed for the function's tasks, but simply 
so debug_report could see them.

I made a class, put my functions in it, and suddenly, they all could 
`see' the objects of interest without the passing and returning of 
objects just for the sake of visibility. Some `self's sprinkled around 
did the work instead.

So, even if you don't make use of further OOP features (as I am 
learning to do on other threads), classes give you a namespace option 
between globals and locals -- `continentals' if you like ;-)

HTH, and looking forward to more expert explanations,
Brian vdB
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed with script to batch-create shapefiles

2005-02-16 Thread Danny Yoo


On Wed, 16 Feb 2005, Bill Mill wrote:

  I have several thousand files in dBaseIV format that I need to convert
  to shapefiles for use in ArcGIS. I've written a script (see below) to
  automate this process but thus far have been unable to get it to work.
  I suspect that there's a simple reason for this, but I'm a complete
  novice with Python and have been unable to find it.

 Boil your question down into something smaller, and then ask it with
 the appropriate information. I suggest reading
 http://www.catb.org/~esr/faqs/smart-questions.html .


Hi Chris,

Yes, at the moment, without even a clue what kind of problem there is,
there's little we can do.  We don't have dBase on our system, so the kind
of diagnostics we have access to is limited to what you tell us.  *grin*

We just don't have enough information, and telling us that something is
going wrong isn't enough for us to do a good analysis.  Let's try
pinpointing what you mean by not working.


I notice that your code has the following structure:

###
try:
## .. do a bunch of stuff
except:
gp.AddMessage(gp.GetMessages(2))
print gp.GetMessages(2)
###

This is a blanket try/except block that catches everything.  This kind of
exception handler tends to disguise problems in the code that have nothing
to do with dBaseIV.  I'm also not sure at all if it's the right thing for
the program to ignore the error and try to continue working with the 'gp'
object.


Try to make exceptional conditions yell out when an exception occurs. That
may make it much easier to see the problems at hand.  Can you add the
following import to your program?

###
import traceback
###

Also modify the except block to this:

###
try:
## .. do a bunch of stuff
except:
traceback.print_exc()
###

These changes use the excellent 'traceback' error-tracing module:

http://www.python.org/doc/lib/module-traceback.html

and traceback.print_exc() will print out the details of errors that occur
in the try block.  We have to do what we can to get some useful
information what's going wrong, before continuing to work on this problem.



Good luck to you!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed with script to batch-create shapefiles

2005-02-16 Thread Jeff Shannon
On Wed, 16 Feb 2005 21:37:10 +, Chris Bromley
[EMAIL PROTECTED] wrote:

 Any help would be greatly appreciated!

Others have already pointed out that we will have a hard time helping
without a bit more information.  But I've noticed something odd in
your code -- it probably doesn't have anything to do with your
problem, but it seems like an awkward idiom to me.

 fc = fcs.next()
 
 while fc:
 # [...]
 fc = fcs.next()

This, it seems to me, is equivalent to (but less readable than) the following:

.for fc in fcs:
.# [...]

If you're going to do something with every member of a list, then it's
much more straightforward to use a for loop (which automatically
tracks the iteration) than to use a while loop and manually adjusting
the loop-controlling expression.

Actually, it occurs to me that this *might* cause a confusing result
in your code.  Presuming that fcs is a standard iterator (as your
usage of next() suggests), then calling next() on an exhausted
iterator will raise a StopIteration exception.  The for loop will
automatically handle that, but with your while loop it would be caught
by the following bare except statement.  That means that you'll run
(what I presume to be) your error-handling code even when you
successfully convert every member of fcs...

Jeff Shannon
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Larger program organization

2005-02-16 Thread Kent Johnson
Terry Carroll wrote:
On Fri, 11 Feb 2005, Bob Gailer wrote:

Whenever you find yourself writing an if statement ask whether this
would be better handled by subclasses. Whenever you find yourself about
to write a global statement, consider making the variables properties of
a class.

Bob -- 

Brian already asked for an explanation of your first statement, and I 
found the ensuing discussion very instructive.

Can you explain the second?  As an aesthetic point, I hate globals, and 
I'd love a discussion with some examples of using class variables as a way 
of avoiding this.
Global variables are one way to make state persist across function calls. Here's a toy example that 
might give you the idea. Suppose you want to write a function that keeps a running total. You could 
do something like this (not recommended!):

total = 0
def addToTotal(inc):
  global total
  total += inc
Every time you call addToTotal, total is incremented.
This is already a poor design.
- There is no encapsulation - to increment the total, you call a function, to view the total you 
look at the global variable.
- There is no API - to reset the total you would have to set the global variable.

You could try to fix this by adding more functions:
def printTotal():
  print 'Total is', total
def resetTotal():
  global total
  total = 0
That's a little better, maybe. But there are other problems:
- You can only have one total. What if you want two different totals?
- Your global namespace has extra names - total, addToTotal, etc.
For short scripts this structure can work, but for larger projects it gets unwieldy. OOP to the 
rescue! How about a Total class?

class Total:
  def __init__(self):
self.reset()
  def add(self, inc):
self.total += inc
  def print(self):
print 'Total is', self.total
  def reset(self):
self.total = 0
You can use this like this:
t = Total()
t.inc(5)
t.print()
t.reset()
Now everything is wrapped up in a nice neat package. There is a clear, consistent API, no namespace 
pollution, and you have a reusable object.

You might also be interested in this essay: 
http://www.pycs.net/users/323/stories/15.html
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Active Python

2005-02-16 Thread Robert Campbell



Hi,
I am not a programmer, but have decided to learn Python. I am 
wondering if anyone has used the Activestate ActivePython and what are the 
advantages/disadvantages of using it rather than the standard Python 
tools.

Robert
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Reading/writing Wave files

2005-02-16 Thread Tony Cappellini

After looking at the Python docs for the wave module, I'm a bit puzzled as 
to how to use it.

Does anyone have an example I can browse?
If I write to a wave file, is the data I write actually audible, if I use 
Winamp or some other wave player, or is it more complicated than that?
Is the data I write actually part of the content of the wave file, or do I 
have to manually handle the file structure of the wave file too (the part 
that is unique to wave files, that is)?

thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor