Re: [Tutor] Exception Handling

2008-12-29 Thread Alan Gauld


David da...@abbottdavid.com wrote

Is this the correct way to handle a ValueError exception and should 
I get in the practice of catching them?


Yes and Yes.

Although I woulfd move the except clause up to just after the input 
section

(which is where the errors will be raised). A couple of other comments
below:


while True:
try:
yr = int(raw_input(What year were you born? ))
mn = int(raw_input(What month were you born? ))
dy = int(raw_input(What day were you born? ))
curr_date = time.strftime(%Y %m %d, time.gmtime())

ynum = int(time.strftime(%Y, time.gmtime())) - int(yr)
mnum = int(time.strftime(%m, time.gmtime()))
dnum = int(time.strftime(%d, time.gmtime()))
mn = int(mn)
dy = int(dy)


Put the except here, its easier to see where the error came from.
And since the error message only applies to these int() calls its
more accurate.


if mn - mnum:
print You are %i % ynum, years old.


This is an odd use of string formatting, more usually you
would only use one string:

print You are %i years old % ynum

Either that or just insert the value and not use formattting:

print You are, ynum, years old.


else:
ret = int(ynum) - 1


You don't need the int conversion here since yuou already
did it at the input stage. But...


print You are %i % ret, years old.


Why not just

   print You are %i % ynum-1, years old.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



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


Re: [Tutor] Exception Handling

2008-12-29 Thread Alan Gauld


bob gailer bgai...@gmail.com wrote

Also IMHO it is bad design to put a lot of code inside a try block. 
In this case the user might make a mistake on day and then is forced 
to reenter the year and month!


Obviously there is no absolute rule here but I disagree.
One of the biggest advantages of try/except error handling is
that it keeps the mess of handling errors out of the main logic
of the code. This has two effects:
1) Code that is much easier to read
2) a lot less error handling code

Using big bite try/except does mean the except clauses
become more complex if you want to find out exactly which
line caused the error, as in the example above, but it can
be done by examining the traceback, but in general I much
prefer to wrap logical blocks of code using try/except rather
than only one or two lines

Better to write a function for requesting an integer from the user 
which loops until the user gets it right (with some way to escape if 
he gets frustrated and just wants to quit.


And this I agree with. If you do want to check each line use a 
function
that incorporates the checking within it and call that to get a 
guaranteed

result. And that keeps both Bob and I happy with the try/excepts
stylistically speaking :-)

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



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


Re: [Tutor] Printing the code of a function

2008-12-29 Thread Alan Gauld


wormwood_3 wormwoo...@yahoo.com wrote

I am wondering if there is a way to print out the code of a defined 
function.


Its not reliable but I think you can use

func.func_code.filename
func.func_code.firstlineno

To find the first line of code in the original source file.
Its up to you to figure out the last line though! I guess checking
for the next line with equivalent indentation might work.

But I'm not sure how much good it would do you... unless you
were writing a debugger maybe?

Alan G


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


[Tutor] optional parameter in list comprehension

2008-12-29 Thread prasad rao
hello!I am a novice looking up to the tutor as my Guide.
I got a problem   while using optional parameter.

#! user/bin/env python
import os

def myfiles(directory,extension=None):
for x in [os.path.join(x,i) for x,y,z in os.walk(directory)\
for i in z if i.endswith(extension)]:print x

if __name__=='__main__':
  import sys
  myfiles(sys.argv[1],sys.argv[2])

 myfiles.myfiles('C:\\python26')

Traceback (most recent call last):
  File pyshell#17, line 1, in module
myfiles.myfiles('C:\\python26')
  File C:\Python26\lib\site-packages\myfiles.py, line 6, in myfiles
for i in z if i.endswith(extension)]:print x
TypeError: expected a character buffer object
 myfiles.myfiles('C:\\python26','doc')
C:\python26\Doc\examples.doc

How can I rectify this?

Thanks

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


Re: [Tutor] optional parameter in list comprehension

2008-12-29 Thread Dj Gilcrease
def myfiles(directory,extension=None):
for x in [os.path.join(x,i) for x,y,z in os.walk(directory)\
if extension:
for i in z if i.endswith(extension)]:print x


Dj Gilcrease
OpenRPG Developer
~~http://www.openrpg.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] optional parameter in list comprehension

2008-12-29 Thread bob gailer

Dj Gilcrease wrote:

def myfiles(directory,extension=None):
for x in [os.path.join(x,i) for x,y,z in os.walk(directory)\
if extension:  SYNTAX ERROR!
for i in z if i.endswith(extension)]:print x

  


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


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


Re: [Tutor] optional parameter in list comprehension

2008-12-29 Thread bob gailer

prasad rao wrote:

hello!
I am a novice looking up to the tutor as my Guide.
I got a problem   while using optional parameter.

#! user/bin/env python
import os

def myfiles(directory,extension=None):


change that to def myfiles(directory,extension=):


for x in [os.path.join(x,i) for x,y,z in os.walk(directory)\
for i in z if i.endswith(extension)]:print x

if __name__=='__main__':

  import sys
  myfiles(sys.argv[1],sys.argv[2])

 myfiles.myfiles('C:\\python26')

Traceback (most recent call last):
  File pyshell#17, line 1, in module
myfiles.myfiles('C:\\python26')
  File C:\Python26\lib\site-packages\myfiles.py, line 6, in myfiles
for i in z if i.endswith(extension)]:print x
TypeError: expected a character buffer object
 myfiles.myfiles('C:\\python26','doc')
C:\python26\Doc\examples.doc

How can I rectify this?

Thanks 


Prasad



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



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


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


Re: [Tutor] Exception Handling

2008-12-29 Thread spir
On Mon, 29 Dec 2008 09:10:45 -
Alan Gauld alan.ga...@btinternet.com wrote:

 
 bob gailer bgai...@gmail.com wrote
 
  Also IMHO it is bad design to put a lot of code inside a try block. 
  In this case the user might make a mistake on day and then is forced 
  to reenter the year and month!
 
 Obviously there is no absolute rule here but I disagree.
 One of the biggest advantages of try/except error handling is
 that it keeps the mess of handling errors out of the main logic
 of the code. This has two effects:
 1) Code that is much easier to read
 2) a lot less error handling code
 
 Using big bite try/except does mean the except clauses
 become more complex if you want to find out exactly which
 line caused the error, as in the example above, but it can
 be done by examining the traceback, but in general I much
 prefer to wrap logical blocks of code using try/except rather
 than only one or two lines
 
I often use the else clause of try...except. This allows putting only the
minimum problematic code lines inside the try block, which is good both for
legibility andto avoid catching unexpected errors. The else will be executed
only in case of no exception:

try:
problematic_instructions
except ExceptionType, exception:
expected_exception_handler
else:
further_standard_process

denis

--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing the code of a function

2008-12-29 Thread spir
On Mon, 29 Dec 2008 09:18:43 -
Alan Gauld alan.ga...@btinternet.com wrote:

 
 wormwood_3 wormwoo...@yahoo.com wrote
 
  I am wondering if there is a way to print out the code of a defined 
  function.
 
 Its not reliable but I think you can use
 
 func.func_code.filename
 func.func_code.firstlineno
 
 To find the first line of code in the original source file.
 Its up to you to figure out the last line though! I guess checking
 for the next line with equivalent indentation might work.
 
 But I'm not sure how much good it would do you... unless you
 were writing a debugger maybe?
 
 Alan G

I would do it so by parsing source file:

* (convert indents to tabs (easier to parse))
* search for a line that start with (n indents) + def func_name
* record all following lines that start with (n+1 indents) or more
* stop where a line starts with (n indents) or less

denis

--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Printing the code of a function

2008-12-29 Thread Kent Johnson
On Sun, Dec 28, 2008 at 8:49 PM, wormwood_3 wormwoo...@yahoo.com wrote:
 Hello all,

 This might be trivially easy, but I was having a hard time searching on it
 since all the component terms are overloaded:-) I am wondering if there is a
 way to print out the code of a defined function.

If the source code is available try inspect.getsource().

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


[Tutor] Modifying a QIF

2008-12-29 Thread Eduardo Vieira
Hello, this weekend I had fun using Python for text processing. I
needed to change a qif converted from a ofx, using the tool MT2OFX
(http://www.xs4all.nl/~csmale/mt2ofx/en/index.htm)
I wanted to change transactions like these:
D11/14/2008
MCHEQUE 102 17590807;Cheque or Preauth. Debit
T-500.00
N102
^

Into this:
D11/14/2008
MCHEQUE 102 17590807;Cheque or Preauth. Debit
T-500.00
N102
PLorne Koehn
LHousing:Rent

== That is, insert those given Payee and Category if the transaction
was a cheque of 500.00

I came up with these two versions and would like to know which should
be more efficient or practical. Could you point improvements?
VERSION ONE:
f = open('cibc.QIF', 'r').readlines()
for line in range(len(f)):
if f[line] == 'T-500.00\n':
f[line+1] += 'PLorne Koehn\nLHousing:Rent\n'

new = open('cibc.QIF', 'w')
new.writelines(f)

VERSION TWO:
f = open('cibc.QIF', 'rw')
g = open('newresult.qif', 'w')
flag = 0
for line in f:
if line == 'T-500.00\n':
flag = 1
elif line.startswith('N') and flag:
flag = 0
line += 'PLorne Koehn\nLHousing:Rent\n'

g.write(line)

f.close()

#==

One thing like about version 1 is that I can overwrite the same
file, and don't need to create another one. I haven't figured out how
to do the same with the second version and overcoming the IOError.

Thanks for your attention

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


Re: [Tutor] Modifying a QIF

2008-12-29 Thread spir
On Mon, 29 Dec 2008 13:18:55 -0700
Eduardo Vieira eduardo.su...@gmail.com wrote:

 Hello, this weekend I had fun using Python for text processing. I
 needed to change a qif converted from a ofx, using the tool MT2OFX
 (http://www.xs4all.nl/~csmale/mt2ofx/en/index.htm)
 I wanted to change transactions like these:
 D11/14/2008
 MCHEQUE 102 17590807;Cheque or Preauth. Debit
 T-500.00
 N102
 ^
 
 Into this:
 D11/14/2008
 MCHEQUE 102 17590807;Cheque or Preauth. Debit
 T-500.00
 N102
 PLorne Koehn
 LHousing:Rent
 
 == That is, insert those given Payee and Category if the transaction
 was a cheque of 500.00
 
 I came up with these two versions and would like to know which should
 be more efficient or practical. Could you point improvements?
 VERSION ONE:
 f = open('cibc.QIF', 'r').readlines()
 for line in range(len(f)):
 if f[line] == 'T-500.00\n':
 f[line+1] += 'PLorne Koehn\nLHousing:Rent\n'
 
 new = open('cibc.QIF', 'w')
 new.writelines(f)
 

I would change 'line' -- 'line_nr' or 'lineno'
or
for line,index in enumerate(f)
no!
for index,line in enumerate(f)
;-)

 VERSION TWO:
 f = open('cibc.QIF', 'rw')
 g = open('newresult.qif', 'w')
 flag = 0
 for line in f:
 if line == 'T-500.00\n':
 flag = 1
 elif line.startswith('N') and flag:
 flag = 0
 line += 'PLorne Koehn\nLHousing:Rent\n'
 
 g.write(line)
 
 f.close()
 
 #==
 
 One thing like about version 1 is that I can overwrite the same
 file, and don't need to create another one. I haven't figured out how
 to do the same with the second version and overcoming the IOError.

maybe by first writing on a string instead directly to a file -- then flush the
whole text to the same file:

text =# replaces g
...
text += line
...
f = open('cibc.QIF', 'w')
f.write(text)

 Thanks for your attention
 
 Edu
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 


--
la vida e estranya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception Handling

2008-12-29 Thread Alan Gauld

spir denis.s...@free.fr wrote

I often use the else clause of try...except. This allows putting 
only the
minimum problematic code lines inside the try block, which is good 
both for
legibility andto avoid catching unexpected errors. The else will be 
executed

only in case of no exception:

try:
problematic_instructions
except ExceptionType, exception:
expected_exception_handler
else:
further_standard_process



Thats exactly what I try to avoid. The big win for me in try/except is
that I can put the whole logic of a function together with no error
code confusing the picture. The above is no better than the old
BASIC style error handling

problemInstruction
if errorcode == XXX:
   handle error
further instruction

I find that much harder to follow the normal case code than:

try:
   problematic instructions
   more instructions
   more problems
except Error1
   handleError1
except Error2:
   handleError2

Now I can see the real algorithm and the errors are all tiucked out of
the way at the bottom where I don't need to read them until its
necessary.

Assuming you don't wrte functions that are hundreds of lines long
that doesn't cause me any problerms when debugging but greatly
increases the readability

The only somewhat valid case for doing line by line exceptions is
IMHO the one that started this - where users are entering input
and would need to start right at the beginning in the event of an
error. But as Bob pointed out you can avoid that by writing
a convertion function to do the error handling and validation and
call it repeatedly.

But it is largely a matter of personal taste.

Alan G. 



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