I'm finally cracking open the Python Style Guide. I've been programming python for years now so I thought I'd join the club.
In addition to all of the nifty tools available to speed up and optimize python code, there are a few utilities out there to help with coding style. PyLint is a program which analyzes source code and reports lines which do not follow the PEP 8 coding convention. There is another program called CloneDigger which looks through source code and points out duplicate code.
Summary of Guidelines to Improve Python Coding Style:
- Variables
- Global variables should be ALL_CAPS_WITH_UNDERSCORES
- Non-public variables within classes should be prefixed with an underscore and lowercase (_private_list = [])
- Public variables should be lowercase
- Boolean variables should be have "is" or "has" (is_full = True)
- Avoid generic names
- Classes
- Should be named using the CamelCase convention
- If a class will be a base class, prefix the classname with "Base"
- Functions
- Names of functions and methods should be lowercase and underscore separated (do_something_with_this)
- Watch out for custom functions which share names with built-in functions
- If this does happen and one can't find a better name, then add a trailing underscore to the custom function
- Arguments names and contents should be decided through an iterative design process
- Also, do not use spaces around the "=" sign used to assign the default parameter for keyword arguments
- Be careful with *args and **kw. These can cause problems if abused.
- Don't implement "type" checking using the assert command
- Conditionals
- When check to see if an object is true, use "if object:" rather than "if object == True" or "if object is True"
- When checking to see if an object is of a certain "type" (integer, string, etc), do not use "if type(obj) == type(int):", use "if isinstance(obj, int):"
- What's "False" in Python?:
- None
- False
- Zero (of any numeric type)
- Any empty sequence or mapping ({},'', [], ())
- instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value
False - Modules and Packages
- Usually has a lib suffix (mathlib)
- Be careful to ensure that any process requiring the use of several functions strung together are consolidated into an independent "pipeline" function
- General Coding
- Clarity over cleverness
- Try to keep code as short as possible--short enough to fit on the screen without having to scroll rampantly
- When a class start to have about 10 or more methods, it is time to re-evaluate the contents of the class and possibly split that larger class into a number of smaller classes
- Use lambda functions for functions that will only be run once or twice. Otherwise, create a defined function
- Use spaces around arithmetic operators
- Import statements should always be on separate lines
- Avoid extraneous whitespace immediately inside parentheses, brackets, or braces. Also before colons



excellent summary for those of us too lazy to go through the looong document
ReplyDeleteNot trying to be a tech nerd, but CamelCase is actually CapsCase. This is camelCase ;)
ReplyDelete@Anonymous
ReplyDeleteInteresting. I didn't know that. Wikipedia actually defines two separate types of camel case, "upper camel case" and "lower camel case."
Concise. Very good article.
ReplyDeleteDon't forget when testing for None, use "if object is None". Assuming that None is False is bad.
ReplyDeleteI used to add a pep8 execution as a pre-commit hook into local repositories
ReplyDeleteI have attached flake8 to my editor (on buffor save). It's wrapper around pep8 and pylint :) Just need to fix marked lines
ReplyDeleteSome time ago I also put together some naming examples (skip right to Examples for the TLDR version): http://www.markus-gattol.name/ws/python.html#naming_conventions
ReplyDeleteThe SublimeLinter plugin for Sublime Text 2 (avaliable through the package control) does a pretty great job of pep8/PyFlakes checking without having to resort to an outside program.
ReplyDelete