A one-page reference for experienced developers and quick lookups while learning.

Variables & Types

  x = 42              # int
y = 3.14            # float
s = "hello"         # str
b = True            # bool
nothing = None

type(x)             # <class 'int'>
int("42")           # 42
str(42)             # "42"
  

Collections

  lst = [1, 2, 3]                    # list
tup = (1, 2)                       # tuple
d = {"a": 1, "b": 2}              # dict
st = {1, 2, 3}                     # set

lst.append(4)
lst[0], lst[-1], lst[1:3]
d.get("key", default)
d["key"], d.keys(), d.values(), d.items()
st.add(4), st.remove(3)
  

Strings

  f"Hello {name}"                    # f-string
s.lower(), s.upper(), s.strip()
s.split(","), "-".join(lst)
s.replace("a", "b")
s.startswith("Hi"), s.endswith("!")
"abc"[::-1]                        # "cba"
  

Control Flow

  if x > 0:
    ...
elif x < 0:
    ...
else:
    ...

for item in iterable:
    ...
for i in range(10):
    ...
while condition:
    ...

break, continue, pass

# Comprehensions
[x**2 for x in range(10)]
{x: x**2 for x in range(5)}
{x for x in range(10) if x % 2 == 0}
  

Functions

  def func(a, b=0, *args, **kwargs):
    return a + b

lambda x: x ** 2

# Unpacking
a, *rest, z = [1, 2, 3, 4, 5]
func(**{"a": 1, "b": 2})
  

Classes

  class Dog:
    species = "Canis"

    def __init__(self, name):
        self.name = name

    def bark(self):
        return f"{self.name} says woof!"

    @property
    def display(self):
        return self.name

    @staticmethod
    def info():
        return "A dog"

    @classmethod
    def from_dict(cls, d):
        return cls(d["name"])
  

Error Handling

  try:
    risky()
except ValueError as e:
    handle(e)
except (TypeError, KeyError):
    ...
else:
    success()
finally:
    cleanup()

raise ValueError("message")
assert x > 0, "must be positive"
  

File I/O

  from pathlib import Path

p = Path("file.txt")
p.read_text(), p.write_text("content")
p.exists(), p.mkdir(parents=True)

with open("f.txt", "r") as f:
    for line in f:
        process(line)

import json
json.loads(s), json.dumps(obj, indent=2)

import csv
# csv.reader, csv.DictReader, csv.writer
  

Imports & Modules

  import os, sys, math, json, re
from collections import defaultdict, Counter
from datetime import datetime, timedelta
from functools import lru_cache, partial
from itertools import chain, groupby

if __name__ == "__main__":
    main()
  

Common Patterns

  # Context manager
with open("f") as f:
    ...

# Enumerate / zip
for i, val in enumerate(lst):
    ...
for a, b in zip(list1, list2):
    ...

# Sort
sorted(lst, key=lambda x: x.name, reverse=True)
lst.sort(key=str.lower)

# Default dict
dd = defaultdict(list)
dd["key"].append(value)

# Counter
from collections import Counter
Counter("mississippi")

# Decorator
@functools.wraps(func)
def wrapper(*args, **kwargs):
    ...
  

Type Hints

  def greet(name: str) -> str:
    return f"Hi {name}"

def process(items: list[int]) -> dict[str, int]:
    ...

Optional[str], Union[int, str], Callable[[int], str]
  

Async

  async def fetch():
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.json()

asyncio.run(fetch())
await asyncio.gather(task1(), task2())
  

Testing

  pytest tests/ -v
pytest --cov=app tests/
python -m unittest discover
  

Package Management

  python -m venv .venv
source .venv/bin/activate
pip install package
pip freeze > requirements.txt
pip install -r requirements.txt
  

Print this page or bookmark it for quick reference while coding.