Saturday, April 28, 2007

Python revision - Book review

Yesterday i found the book 'Learn to Program using Python' by Alan Gauld in the office. Since i had a few hrs to kill i decide to quickly go through the book.

I have been using python for almost a year now but strangely i have never had any sort of formal training and neither have i learnt python in a structured manner. Its mostly been task based which always makes me wonder if my coding style is indeed the correct way to do things. So i was excited about the prospect of reading this book and learning to do things the right way.

So i sat down to read and within an hr i was on page 100 (which is quite significant considering the book has just 270 pages). I realized that my knowledge of "basic" python was quite good, infact what i was really yearning for was indepth understanding of concepts and good practises and the book didn't quite provide this. That said it was wrong on my part to expect such topics from a book meant to be introductory text for python. That said the book in itself i quite good, it has small chapters and simple language and is a must read for early adopters of the language. I wish i knew about this book a year back.

I did come across a few feature i didn't know about, like:

1. dealing with binary streams, esp using struct.pack(...)

2. nested try/except. I had always hated the fact that you cannot use try-except-finally in a single construct but it never occured to me that i could achieve the same by nesting these clauses,eg.

try:
    try:
       ......
    except:
       .......
finally:
       .....

This ineffect gives me the same functionality as,

try:
    ....
except:
    .....
finally:
    ....

NOTE: this is now allowed in python 2.5

3. Another thing i came across (not in this book but i feel this is the right place to record it) is the technique to create a list from another list.

Earlier i used to do the following:

l = [list of objects with method 'id']
k = []
for obj in l:
    k.append(obj.id())

I always thought this was too much code to achieve too little. So after a bit of searching i discovered the following trick:
k = [obj.id() for obj in l]

Now i create new lists in a single line instead of 3, a 3X productivity improvement :D

No comments: