PEP8 Python style guide Flashcards
To be able to write Pythonic code
What is PEP8?
It’s the style guide for writing Python code - how the code should look/be formatted to maximize readability
PEP stands for Python Enhancement Proposal.
What is PEP20?
The Zen of Python by Tim Peters.
A succinct list of 20 aphorisms about guiding principles of Python design.
import this
What is the recommendation indentation level
4 spaces per indentation level
What is the preferred indentation method - tabs or spaces
Spaces
What should maximum line length be?
79 characters
For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
Should a line break before or after a Binary operator?
Before (follow Donald Knuth’s style) for new code e.g.
income = (gross_wages \+ taxable_interest \+ (dividends - qualified_dividends) - ira_deduction - student_loan_interest)
What are rules for imports?
Imports should usually be on separate lines
import os
import sys
however, ok to do:
from subprocess import Popen, PIPE
How should imports be grouped?
Imports should be grouped in the following order:
Standard library imports.
Related third party imports.
Local application/library specific imports.
You should put a blank line between each group of imports.
Explain block comments
Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment).
Paragraphs inside a block comment are separated by a line containing a single #.
Explain inline comments
Use inline comments sparingly.
An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.
Inline comments are unnecessary and in fact distracting if they state the obvious. Don’t do this:
Explain documentation strings … docstrings
Docstrings should be written for all public modules, functions and classes. They are of format:
”"”Return a foobang
Optional plotz says to frobnicate the bizbaz first.
“””
Can have single line docstrings as well
Naming Conventions: Module
Modules are the actual files e.g. character_input.py
… may contain 0, 1, or more classes
Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.
Naming Conventions: Package
Packages are essentially where code is structured in folders and sub-folders.
Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
Naming Conventions: Class
Class names should normally use the CapWords convention.
CapitalizedWords (or CapWords, or CamelCase
Naming Conventions: Exception
Because exceptions should be classes, the class naming convention applies here. However, you should use the suffix “Error” on your exception names (if the exception actually is an error)
Naming Conventions: Functions and Variables
Function and Variables names should be lowercase, with words separated by underscores as necessary to improve readability.
Naming Conventions: Function and Method arguments
Always use self for the first argument to instance methods.
Always use cls for the first argument to class methods.
If a function argument’s name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)
Naming Conventions: Methods and Instance variables
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
Use one leading underscore only for non-public methods and instance variables.
To avoid name clashes with subclasses, use two leading underscores to invoke Python’s name mangling rules.
Naming Conventions: Constants
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.
What does it mean if code is not Pythonic?
Usually means that these lines of code do not follow the common guidelines and fail to express its intent in what is considered the best (hear: most readable) way.
What is a programming idiom?
Put simply, it is a way to write code
How do you assign to an variable you want to ignore?
Use the double underscore __ e.g below the __ holds the ‘.’ character
filename = ‘foobar.txt’
basename, __, ext = filename.rpartition(‘.’)
How do you create a string from a list?
Use str.join() on an empty string e.g
letters = ['s', 'p', 'a', 'm'] word = ''.join(letters)
How should you read from a file?
Use the with open syntax - this will automatically close files for you.
with open('file.txt') as f: for line in f: print line