As I wrote in Python Style Guide Part 1, Google has put together a really nice style guide summary. This style guide is a list of dos and don’ts for Python programs.
A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.
PEP8 has emerged as the style guide that most projects. it promotes a very readable and eye-pleasing coding style. PEP8 has emerged as the style guide that most projects. it promotes a very readable and eye-pleasing coding style. It’s a well-established convention in the Python community, and in general we should follow these.
The page can be found here: http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
Each style point has a summary for which additional information.
Python Style Rules
Do not terminate your lines with semi-colons and do not use semi-colons to put
two commands on the same line.
Maximum line length is 80 characters.
Use parentheses sparingly.
Indent your code blocks with 4 spaces.
Two blank lines between top-level definitions, one blank line between method
Follow standard typographic rules for the use of spaces around punctuation.
Most .py files do not need to start with a #! line.
Start the main file of a program with #!/usr/bin/python.
Be sure to use the right style for module, function, method and in-line comments.
If a class inherits from no other base classes, explicitly inherit from object.
This also applies to nested classes.
Use the % operator for formatting strings, even when the parameters are all
Use your best judgement to decide between + and % though.
Files and Sockets
Explicitly close files and sockets when done with them.
Use TODO comments for code that is temporary, a short-term solution,
or good-enough but not perfect.
Imports should be on separate lines.
Generally only one statement per line.
If an accessor function would be trivial you should use public variables
instead of accessor functions to avoid the extra cost of function calls in Python.
When more functionality is added you can use property to keep the syntax
module_name, package_name, ClassName, method_name, ExceptionName,
function_name, GLOBAL_CONSTANT_NAME, global_var_name,
instance_var_name, function_parameter_name, local_var_name.
Even a file meant to be used as a script should be importable and a mere import
should not have the side effect of executing the script’s main functionality.
The main functionality should be in a main() function.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.