Preface
Change List
Version 1.1, February 2, 2013
Version 1.2, February 17, 2013
Contents
Control Structures and Functions
If Statements
Avoid comparing directly to True, False, or None
Avoid repeating variable name in compound if statement
Avoid placing conditional branch code on the same line as the colon
For loops
Use the enumerate function in loops instead of creating an ``index'' variable
Use the in keyword to iterate over an iterable
Use else to execute code after a for loop concludes
Functions
Avoid using '', [], and {} as default parameters to functions
Use *args and **kwargs to accept arbitrary arguments
Working with Data
Lists
Use a list comprehension to create a transformed version of an existing list
Use the * operator to represent the ``rest'' of a list
Dictionaries
Use the default parameter of dict.get to provide default values
Use a dict comprehension to build a dict clearly and efficiently
Strings
Prefer the format function for formatting strings
Use ''.join when creating a single string for list elements
Chain string functions to make a simple series of transformations more clear
Classes
Use underscores in function and variable names to help mark ``private'' data
Define __str__ in a class to show a human-readable representation
Sets
Use sets to eliminate duplicate entries from Iterable containers
Use a set comprehension to generate sets concisely
Understand and use the mathematical set operations
Generators
Use a generator to lazily load infinite sequences
Prefer a generator expression to a list comprehension for simple iteration
Context Managers
Use a context manager to ensure resources are properly managed
Tuples
Use tuples to unpack data
Use _ as a placeholder for data in a tuple that should be ignored
Variables
Avoid using a temporary variable when performing a swap of two values
Organizing Your Code
Modules and Packages
Use modules for encapsulation where other languages would use Objects
Formatting
Use all capital letters when declaring global constant values
Avoid placing multiple statements on a single line
Format your code according to PEP8
Executable Scripts
Use sys.exit in your script to return proper error codes
Use the if __name__ == '__main__' pattern to allow a file to be both imported and run directly
Imports
Prefer absolute imports to relative imports
Do not use from foo import * to import the contents of a module.
Arrange your import statements in a standard order
General Advice
Avoid Reinventing the Wheel
Learn the Contents of the Python Standard Library
Get to know PyPI (the Python Package Index)
Modules of Note
Learn the contents of the itertools module
Use functions in the os.path module when working with directory paths
Contributors