Cheatography
https://cheatography.com
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 |
Bracket/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
Bracket/etc. sides |
spam(ham[1], {eggs: 2}) |
Around an assignment |
x = 4 * y variable = 4 |
Between a trailing comma and close parenthesis |
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 Conventions
Variable/Function |
lower_case_with_underscores |
Class/Exception |
CapWords |
Non-public methods and instance variables |
_var |
Constants |
UPPER_CASE_WITH_UNDERSCORES |
Dunders |
__var__ |
Structures
Conditional |
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_age(day, month, year=2004): ... |
List comprehension |
[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((lambda x, y: x * y), list) |
|