Production Reference

Python Cheat Sheet

Essential Python syntax, runtime patterns, standard-library helpers, and environment commands worth keeping close while building production code.

Command-firstProduction notesSecurity warningsHardened patterns

Variables & Data Types

10 commands
x = 10

Integer

pi = 3.14

Float

name = "Alice"

String

active = True

Boolean

items = [1, 2, 3]

List (mutable)

coords = (1, 2)

Tuple (immutable)

unique = {1, 2, 3}

Set (unique values)

user = {"name": "A"}

Dictionary

type(x)

Check type

isinstance(x, int)

Type check (preferred)

String Operations

10 commands
f"Hello {name}"

f-string formatting

s.upper() / s.lower()

Case conversion

s.strip()

Remove whitespace

s.split(",")

Split into list

",".join(list)

Join list to string

s.replace("a","b")

Replace substring

s.startswith("hi")

Check prefix

s[1:5]

Slice (index 1 to 4)

s[::-1]

Reverse string

len(s)

String length

List Operations

10 commands
lst.append(x)

Add to end

lst.insert(0, x)

Insert at index

lst.pop()

Remove & return last

lst.remove(x)

Remove first occurrence

lst.sort()

Sort in place

sorted(lst)

Return sorted copy

lst[:3]

First 3 elements

lst[-1]

Last element

[x*2 for x in lst]

List comprehension

[x for x in lst if x>0]

Filtered comprehension

Dictionary Operations

10 commands
d["key"]

Get value (KeyError if missing)

d.get("key", default)

Get with default

d["key"] = value

Set value

del d["key"]

Delete key

"key" in d

Check key exists

d.keys()

All keys

d.values()

All values

d.items()

Key-value pairs

d.update(d2)

Merge dictionaries

{**d1, **d2}

Merge (Python 3.5+)

Control Flow

9 commands
if x > 0:

If statement

elif x == 0:

Else if

else:

Else

for x in range(10):

For loop

for i, v in enumerate(lst):

Loop with index

while condition:

While loop

break / continue

Loop control

x if cond else y

Ternary operator

match value:

Pattern matching (3.10+)

Functions

8 commands
def fn(x, y=10):

Function with default

def fn(*args):

Variable positional args

def fn(**kwargs):

Variable keyword args

lambda x: x * 2

Anonymous function

@decorator

Decorator syntax

-> int:

Return type hint

return a, b

Return tuple

yield x

Generator function

Error Handling

5 commands
try: ... except Exception as e:

Catch exception

finally:

Always executes

raise ValueError("msg")

Raise exception

assert x > 0, "msg"

Assert condition

with open("f") as f:

Context manager

File I/O

8 commands
open("f.txt", "r")

Read mode

open("f.txt", "w")

Write (overwrite)

open("f.txt", "a")

Append mode

f.read()

Read entire file

f.readlines()

Read lines as list

f.write("text")

Write string

json.load(f)

Parse JSON file

json.dumps(obj)

Object to JSON string

OOP (Classes)

9 commands
class Dog:

Define class

def __init__(self):

Constructor

self.name = name

Instance variable

@property

Getter property

@staticmethod

No self/cls access

@classmethod

Access via cls

class B(A):

Inheritance

super().__init__()

Call parent constructor

@dataclass

Auto __init__, __repr__

Useful Built-ins

9 commands
map(fn, iterable)

Apply fn to each

filter(fn, iterable)

Keep if fn returns True

zip(a, b)

Pair elements

any([True, False])

True if any True

all([True, True])

True if all True

sum(lst)

Sum of numbers

max(lst) / min(lst)

Max / min value

abs(-5)

Absolute value

round(3.14, 1)

Round to 1 decimal

Virtual Environments

7 commands
python -m venv venv

Create venv

source venv/bin/activate

Activate (Linux/Mac)

venv\Scripts\activate

Activate (Windows)

deactivate

Deactivate venv

pip install pkg

Install package

pip freeze > req.txt

Save dependencies

pip install -r req.txt

Install from file

Common Imports

7 commands
import os, sys, json

Standard library

from pathlib import Path

Modern file paths

from datetime import datetime

Date/time

from collections import Counter, defaultdict

Special containers

from typing import List, Dict, Optional

Type hints

import re

Regular expressions

from functools import lru_cache

Memoization

Async / Await

10 commands
import asyncio

Import async module

async def fetch():

Define async function

await coroutine()

Wait for async result

asyncio.run(main())

Run async entry point

asyncio.gather(a(), b())

Run concurrently

asyncio.create_task(coro())

Schedule in background

async for item in aiter:

Async iteration

async with aopen('f') as f:

Async context manager

asyncio.sleep(1)

Non-blocking sleep

asyncio.Queue()

Async producer-consumer queue

Decorators & Metaclasses

10 commands
@functools.wraps(fn)

Preserve wrapped fn metadata

@functools.lru_cache(maxsize=128)

Memoize function results

@functools.cache

Unbounded cache (3.9+)

@contextmanager

Turn generator into context mgr

@classmethod / @staticmethod

Class-level methods

@abstractmethod

Force subclass implementation

@overload

Type-hint multiple signatures

type(name, bases, dict)

Create class dynamically

class Meta(type):

Define metaclass

class Cls(metaclass=Meta):

Use metaclass

Testing (pytest)

10 commands
pip install pytest

Install pytest

def test_add():

Test function (prefix test_)

assert result == expected

Basic assertion

pytest.raises(ValueError)

Expect exception

@pytest.fixture

Setup/teardown helper

@pytest.mark.parametrize('a,b', [...])

Parameterized tests

pytest -v

Verbose output

pytest -k 'test_name'

Run specific test

pytest --cov=src

Coverage report

monkeypatch.setattr(obj, 'attr', val)

Mock attributes

Advanced Data Structures

10 commands
from heapq import heappush, heappop

Min-heap (priority queue)

from collections import deque

Double-ended queue (O(1) both ends)

from collections import OrderedDict

Insertion-ordered dict

from collections import namedtuple

Lightweight immutable class

from dataclasses import dataclass, field

Auto-generated class methods

from enum import Enum, auto

Enumeration type

from typing import TypeVar, Generic

Generic types

frozenset({1, 2, 3})

Immutable set (hashable)

from bisect import insort, bisect_left

Sorted list operations

from itertools import chain, product, permutations

Combinatorics

Performance & Profiling

10 commands
python -m cProfile script.py

Profile entire script

from line_profiler import profile

Line-by-line profiler

import timeit; timeit.timeit(fn, number=1000)

Benchmark function

sys.getsizeof(obj)

Object memory size

__slots__ = ['x', 'y']

Reduce instance memory 40%

from functools import reduce

Fold/reduce a sequence

from operator import itemgetter

Fast key function for sort

from concurrent.futures import ThreadPoolExecutor

Thread pool

from concurrent.futures import ProcessPoolExecutor

Process pool

from multiprocessing import Pool

Parallel map

Type Hints (Advanced)

10 commands
x: int = 10

Basic type annotation

def fn(x: str) -> bool:

Function signature

Optional[int]

int | None

Union[int, str]

int or str

list[dict[str, Any]]

Nested generic (3.9+)

Literal['a', 'b']

Exact value type

TypeAlias = dict[str, list[int]]

Type alias

Callable[[int], str]

Function type

Protocol

Structural subtyping (duck typing)

mypy script.py

Static type checker