Design

Sunday, April 22, 2012

Python Style Guide

Did you realize Python has a style guide to clarify consistent and readable code? It covers topics such as white space of indentations in-line, capitalization of variable, function, and class names, and formatting of comments. Read Pep8

Now I look at my code examples and see a whole lot of ugly. Some good news is that some of the proper styles can be integrated into your vim configuration. A tab on your keyboard can type four spaces. A red line can be drawn vertically to show when a line exceeds the recommended 79 characters. The other good news is that you can run the pep8 script to find style errors. I am going to make an effort to follow the style guide, as well as improve my names. By using "is" to preface boolean tests, verbs such as "get" prefacing function names, and complete words or widely accepted abbreviations (such as str for string), my code can be more readable. I am also going to make my names something that I can sound out. As my code becomes more complicated, variable class and method names are easier to remember if you can pronounce them out loud. 

To use pep8, you simply install it using pip or easy install, run it against your python file, then read the corrections pep8 expects. Example corrections may be that two empty lines were expected instead of one, max line length was surpassed, or extra spacing was found. The script prints the lines that each instance is found on, so you can easily make changes if you want to comply with the preferred style. Documentation can be found here.

I am reaching a stage in my learning where I am reading more code than I am writing. Ambiguous names, inconsistent capitalization, incorrect spelling, and weird in-line spacing makes reading code more difficult. I did have the mindset that if Python didn't care, why should I? Well, now I do care. Just like when learning a spoken language, reading is an important part of learning how to communicate with the language properly.

No comments:

Post a Comment