Show Menu
Cheatography

Python PEP8 - Jairo Andrades Bueno Cheat Sheet (DRAFT) by

Cheatsheet PEP8 style guide for python and some important structures.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Code Lay-out

Identation
4 spaces
Max. Length
79 characters
Bracke­t/etc. closing
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
Break before binary operator
x = a + b
      + c
Imports
import _ as _
from _ import _, _
String Quotes (both correct)
a = "word"
b = 'word'

Whitespace

Bracke­t/etc. sides
spam(h­am[1], {eggs: 2})
Around an assignment
x = 4 * y
variable = 4
Between a trailing comma
and close parent­hesis
foo = (4,)
Comma/etc. sides
if x == 4: print(x, y); x, y = y, x
Colon sides
arr[3:6], arr[3:6:]
arr[::9]
Operators surround
(try in lowest priority)
x *= 2 + 1
y = (2+5) * (5-1)
Keyword argument
or default value
def func(val, age=18):
    return num(r=­real, i=imag)
Argument annotation
with a default value
def func(sep: AnyStr = None, age=10): ...

Comments

First word
capitalized
# This is a comment
Block
# This is a
# block. Yes.
#
# It is.
Inline
y = x + 1  # Linear
Docstrings
def calc_age():
       ¨¨¨Return the age
       Be careful with the end
       ¨¨¨
 

Naming Conven­tions

Variab­le/­Fun­ction
lower_­cas­e_w­ith­_un­der­scores
Class/­Exc­eption
CapWords
Non-public methods and instance variables
_var
Constants
UPPER_­CAS­E_W­ITH­_UN­DER­SCORES
Dunders
__var__

Structures

Condit­ional
if x == 0:
    ...
elif x == 1:
    ...
else:
    ...
Ternary
y = 0 if x == 0 else x == 1
Match
match x:
    case 0:
        ...
    case 1:
        ...
    case_:
        ...
For in
for i in list:
    ...
While
while x >= 0:
    ...
    x -= 1
Function
def calc_a­ge(day, month, year=2004):
    ...
List compre­hension
[x**2 for x in list if x != 0]
Map
map(lambda x: x**2, list)
Filter
filter­(lambda x: x < 0, list)
Reduce
reduce­((l­ambda x, y: x * y), list)