Archive
Tags
android (3)
ant (2)
beautifulsoup (1)
debian (1)
decorators (1)
django (9)
dovecot (1)
encryption (1)
fix (4)
gotcha (2)
hobo (1)
htmlparser (1)
imaplib (2)
java (1)
json (2)
kerberos (2)
linux (7)
lxml (5)
markdown (4)
mechanize (6)
multiprocessing (1)
mysql (2)
nagios (2)
new_features (3)
open_source (5)
optparse (2)
parsing (1)
perl (2)
postgres (1)
preseed (1)
pxe (4)
pyqt4 (1)
python (41)
raid (1)
rails (1)
red_hat (1)
reportlab (4)
request_tracker (2)
rt (2)
ruby (1)
scala (1)
screen_scraping (7)
shell_scripting (8)
soap (1)
solaris (3)
sql (2)
sqlalchemy (2)
tips_and_tricks (1)
twitter (2)
ubuntu (1)
vmware (2)
windows (1)
zimbra (2)

I have read a lot of bad python code as of recent. The code gets the work done, but it fails in what I consider Python's killer feature, readability. The programmers are not to blame. I have read bad python in books about python programming! I do not want you, as a reader of this blog, to write python poorly. Finding the proper path to pythonic code is easy.

The first piece for study is the offical style guide for python. Written by the father of python, Guido van Rossum, and Barry Warsaw, this document will tell you the pythonic way of placing whitespace, importing modules, documenting code, and more. Following the suggestions here will make your code more readable to others and easier to write for you, but your programming will not be pythonic just yet.

The Zen of Python, by Tim Peters, is the next read and it is a short one. The idea is to give you something easy to remember that will make you think in a pythonic fashion. This document is available inside of python if you import this.

The final piece is What is Pythonic?, by Martijn Faassen. Here you will find real examples of what is pythonic and what is not.

After reading these, you have no excuse to write ugly python code. I do not want to see this:

from somemodule import * # Wrong, what exactly are we importing?
import somemodule # Good
from somemodule import something # Fine too

or this:

h='somevalue' # Bad, what is 'h'?  Needs spaces around the '='.
header = 'somevalue' # Good

or any of this anymore:

# Bad
for i in range(len(somelist)):
    do_something(somelist[i])
# Good
for element in somelist:
    do_something(element)

Pythonic is your new mantra, if you intend to write python. If you want more to read, take a look at the rest of the Python Enhancement Proposals, specifically the Finished PEPs. For examples of pythonic code, check out the standard python modules or any of the python code featured on this blog.

Posted by Tyler Lesmann on January 18, 2009 at 13:28
Tagged as: python tips_and_tricks