Language :: Python

Python Handbook

Python is a dynamically typed language used for automation, web services, data analysis, and machine learning. CPython 3.13 introduced an optional free-threaded build. The default build uses the global interpreter lock (GIL).

Pick Python when

  • Data science, ML, or AI — NumPy, Pandas, scikit-learn, PyTorch, TensorFlow, and Jupyter are all Python-first. No other language comes close for this domain.
  • Rapid prototyping — Python lets you write working code in a fraction of the time it takes in C++, Java, or Go. Ideal when you're still exploring the problem space.
  • Scripting and automation — file system operations, shell pipelines, REST API calls, web scraping (BeautifulSoup, Playwright), and CI scripts are all Python's sweet spot.
  • Web APIs with low-to-medium traffic — FastAPI and Django REST framework are excellent for building services quickly. FastAPI + async is competitive in throughput benchmarks.
  • You need a huge package ecosystem — PyPI has 500k+ packages. Whatever you need, it's probably already there.
  • Teaching and learning — Python's syntax is minimal, errors are clear, and the REPL gives instant feedback. It's the standard first language in academia.

Think twice before choosing Python when

  • Raw CPU performance matters — Python (CPython) is typically 10–100× slower than compiled languages. For compute-heavy code, use NumPy/PyTorch (which drop to C under the hood), Cython, or switch to a compiled language.
  • True parallelism is required — the GIL prevents multiple OS threads from running Python bytecode simultaneously. Use multiprocessing or asyncio for concurrency; or switch to Go/Rust for heavy parallel workloads.
  • You're deploying to mobile or embedded — CPython is heavy. MicroPython exists for microcontrollers but is limited.
  • Type safety at scale — Python's type hints are optional and only checked by external tools (mypy, pyright). Large teams maintaining complex Python codebases invest heavily in tooling to get the safety that TypeScript or Go give by default.

Python vs. its closest alternatives

  • Python vs JavaScript (Node) — both are interpreted and dynamically typed. Python dominates data/ML; JS/Node dominates the browser and real-time web. For a pure backend API, both are fine; Node handles more concurrent connections per machine.
  • Python vs Go — Go is much faster, compiles to a single binary, and has first-class concurrency. Python is far quicker to write. Use Go when you ship a long-running service; Python when you need results today.
  • Python vs R — R is unmatched for statistical analysis and publishing. Python has overtaken R in ML/DL thanks to PyTorch and scikit-learn. New projects: Python unless you're in academic statistics.

Your First Program

Install Python 3 tooling using the Resources links. Save this program as hello.py.

The indented body belongs to greet. The f-string inserts the argument into the message, and print displays the returned string.

python
def greet(name):
    return f"Hello, {name}!"

print(greet("Ada"))

Run these commands from the directory containing the source file. The output is Hello, Ada!

bash
python hello.py

Resources

Topics

Variables & Types

Objects have runtime types. A name can be rebound to an object of a different type.

Assignment binds a name to a value. Unpacking assigns several names at once, so the swap evaluates both old values before assigning either name. The uppercase constant name is a convention. The interpreter allows reassignment.

Binding names to objects

Follow two names that initially refer to the same list.

python
items = ['tea']
alias = items
alias.append('coffee')
print(items)  # ['tea', 'coffee']
alias = []
print(items)  # ['tea', 'coffee']

Append mutates the shared list. The final assignment binds alias to a new list and leaves items bound to the original.

Additional examples

Bind and inspect values

python
# No declaration needed — just assign
age = 30
pi = 3.14159
name = 'Alice'
active = True
nothing = None

# Type hints (list[int] requires Python 3.9+)
score: float = 9.5
items: list[int] = [1, 2, 3]

# Check types
type(age)             # <class 'int'>
isinstance(age, int)  # True

Annotations describe expected types and type reports the runtime class.

Unpack and swap values

python
# Multiple assignment
a, b, c = 1, 2, 3
x = y = z = 0

# Swap
a, b = b, a

# Constants (convention — Python doesn't enforce)
MAX_RETRIES = 3

Python evaluates the right-hand side before assigning the targets, so swapping needs no temporary variable.

Strings

Strings represent Unicode text and bytes represent encoded data. Choose encodings at I/O boundaries and avoid treating binary payloads as text.

Strings are immutable. Replace and upper return results without changing s. In a slice, the stop position is excluded, so positions 1 through 3 give ell. A negative step visits the characters in reverse order.

Format values with f-strings

python
s = 'hello'

# f-strings (Python 3.6+)
name = 'Alice'
greeting = f'Hello, {name}!'
expr = f'{2 ** 10 = }'   # '2 ** 10 = 1024'

Expressions in braces are evaluated when the string is built.

Search and slice strings

python
s = 'hello'

# Common methods
s.upper()                       # 'HELLO'
s.strip()                       # remove whitespace
s.split(',')                    # split to list
','.join(['a', 'b', 'c'])       # 'a,b,c'
s.replace('h', 'H')
s.startswith('he')
s.endswith('lo')
len(s)                          # 5

# Indexing and slicing
s[0]       # 'h'
s[-1]      # 'o'
s[1:4]     # 'ell'
s[::-1]    # reverse: 'olleh'

String methods return new values. Slice bounds include the start and exclude the stop.

Control Flow

Indentation defines blocks and conditions use truth-value testing. Iterate over values directly and use enumerate when positions are also needed.

The first true branch wins, so 42 is medium. Range excludes its stop value. Enumerate pairs each item with its index, while zip pairs items from two inputs and stops at the shorter one. Continue skips an iteration and break ends the loop.

Choose a branch

python
x = 42

# if / elif / else
if x > 100:
    print('big')
elif x > 10:
    print('medium')
else:
    print('small')

# Ternary (conditional expression)
label = 'even' if x % 2 == 0 else 'odd'

# match-case (Python 3.10+)
match x % 3:
    case 0: print('divisible by 3')
    case 1: print('remainder 1')
    case _: print('remainder 2')

The first matching branch runs. A match statement tests cases in order.

Iterate with indices and pairs

python
# for loop
for i in range(5):          # 0,1,2,3,4
    print(i)

for i in range(2, 10, 2):   # 2,4,6,8
    print(i)

# Enumerate and zip
names = ['Alice', 'Bob']
for i, name in enumerate(names):
    print(i, name)

for a, b in zip([1, 2, 3], ['x', 'y', 'z']):
    print(a, b)

# while with break / continue
n = 10
while n > 0:
    n -= 1

for i in range(10):
    if i == 3: continue
    if i == 7: break
    print(i)

Enumerate adds indices and zip pairs successive elements. Break exits the loop.

Functions

Functions accept positional or keyword arguments and return objects. Defaults are created once at definition time, so use a sentinel such as None when each call needs a fresh mutable object.

The annotations on add describe its input and return types for tools. The variadic function collects extra positional arguments in a tuple and keyword arguments in a dictionary. A bare asterisk makes the following parameters keyword-only. The generator yields values on demand, and the decorator wraps a call to log it.

Create a fresh default list

Use this pattern when callers may supply a list or ask the function to create one.

python
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item('tea'))     # ['tea']
print(add_item('coffee'))  # ['coffee']
order = []
add_item('water', order)
print(order)               # ['water']

Each omitted argument creates a fresh list inside the function. An explicit empty list passes the identity check and receives the new item.

Additional examples

Declare parameters and defaults

python
# Basic function
def add(a: int, b: int) -> int:
    return a + b

# Default arguments
def greet(name: str, greeting: str = 'Hello') -> str:
    return f'{greeting}, {name}!'

# *args and **kwargs
def variadic(*args, **kwargs):
    print(args)    # tuple
    print(kwargs)  # dict

variadic(1, 2, 3, color='red', size=5)

# Keyword-only arguments
def only_keyword(*, name, age):
    print(name, age)
only_keyword(name='Alice', age=30)

Keyword-only parameters must be supplied by name. The variadic parameters collect extra arguments.

Return behavior or yield values

python
# Lambda
double = lambda x: x * 2

# Generators
def countdown(n):
    while n > 0:
        yield n
        n -= 1

# Decorators
import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f'Calling {func.__name__}')
        result = func(*args, **kwargs)
        return result
    return wrapper

@log
def say_hello():
    print('Hello!')

A lambda defines a callable, a generator yields incrementally, and a decorator wraps a function.

Collections

Lists preserve sequences, dictionaries associate keys and values, and sets express uniqueness. Assignment shares objects and an outer copy can retain shared nested values.

Lists

Choose a list for an ordered sequence that you need to edit, such as a queue of tasks you display by position.

python
# List — ordered, mutable
nums = [1, 2, 3, 4, 5]
nums.append(6)
nums.insert(0, 0)
print(nums.pop())    # 6
nums.remove(3)       # remove by value
nums.sort()
print(nums)         # [0, 1, 2, 4, 5]
print(len(nums))    # 5

Pop returns the last item, 6. Remove then deletes the first occurrence of 3, leaving the sorted list [0, 1, 2, 4, 5].

Tuples

Choose a tuple for a fixed group of values, such as the two coordinates of a point.

python
# Tuple — ordered, immutable
point = (10, 20)
x, y = point         # unpack
print(x, y)         # 10 20

Unpacking assigns 10 to x and 20 to y. A tuple holds fixed references, so a mutable object inside it can still change.

Sets

Choose a set to test membership, remove duplicates, or compare groups of unique values.

python
# Set — unordered, unique
s = {1, 2, 3, 2, 1}   # {1, 2, 3}
s.add(4)
s.discard(2)
s1 = {1, 2, 3}
s2 = {2, 3, 4}
print(sorted(s1 & s2))  # [2, 3]
print(sorted(s1 | s2))  # [1, 2, 3, 4]
print(sorted(s1 - s2))  # [1]

Intersection finds the common values 2 and 3. Union combines both sets, and the difference keeps only 1 from the left set. Sets have no guaranteed iteration order.

Dictionaries

Choose a dictionary when a key identifies the value you need, such as a field in a profile.

python
# Dict — key/value pairs
person = {'name': 'Alice', 'age': 30}
person['city'] = 'Paris'
print(person.get('missing', 'default'))  # default
del person['age']

for key, value in person.items():
    print(f'{key}: {value}')  # name: Alice, then city: Paris

Get returns the fallback without adding a key. After deleting age, items yields name and city in insertion order.

Comprehensions

Comprehensions build collections through iteration and filtering. Use a loop when complex branches or side effects make the expression difficult to read.

Read a comprehension in loop order. For each input, apply the condition if present, then produce the expression at the front. The nested example visits every pair of coordinates. The generator expression produces one square at a time as sum consumes it.

Filter and transform in one pass

Use a comprehension to extract the squares of the even numbers in a short list.

python
numbers = [1, 2, 3, 4]
squares = [number ** 2 for number in numbers if number % 2 == 0]
print(squares)  # [4, 16]

The condition discards 1 and 3 before squaring. The surviving inputs keep their original order in the result.

Transform, filter, and combine lists

Use a list comprehension when you need the results immediately, in input order. The nested form pairs each x with every y.

python
# List comprehension
squares = [x**2 for x in range(10)]
evens   = [x for x in range(20) if x % 2 == 0]
pairs   = [(x, y) for x in range(3) for y in range(3)]

print(squares[:3], evens[:3], pairs[:4])  # [0, 1, 4] [0, 2, 4] [(0, 0), (0, 1), (0, 2), (1, 0)]

Build a lookup dictionary

Use a dictionary comprehension when each result should be retrievable by key. Here the number is the key and its square is the value.

python
# Dict comprehension
squared_map = {x: x**2 for x in range(6)}

print(squared_map[3])  # 9

Keep unique results

Use a set comprehension when repeated results should collapse. Sort the lengths only when displaying them.

python
# Set comprehension
unique_lengths = {len(w) for w in ['hi', 'hello', 'hey']}

print(sorted(unique_lengths))  # [2, 3, 5]

Generate values on demand

Use a generator expression when a consumer such as sum can process each value once. After summing, the generator is exhausted.

python
# Generator expression (lazy — no list created)
gen = (x**2 for x in range(1000))
total = sum(gen)

print(total, list(gen))  # 332833500 []

Classes & OOP

Classes combine attributes and behavior. Distinguish instance state from class attributes, particularly when storing mutable collections.

Attributes assigned through self belong to one instance. A class attribute is shared until an instance shadows it, so putting a mutable list on the class can accidentally share changes between objects.

Override methods in a subclass

python
class Animal:
    species = 'Unknown'   # class variable

    def __init__(self, name: str, sound: str):
        self.name = name        # instance variable
        self._sound = sound     # convention: protected

    def speak(self) -> str:
        return f'{self.name} says {self._sound}'

    def __repr__(self) -> str:
        return f'Animal({self.name!r})'

    @classmethod
    def from_dict(cls, data: dict) -> 'Animal':
        return cls(data['name'], data['sound'])

    @staticmethod
    def is_valid_name(name: str) -> bool:
        return len(name) > 0


class Dog(Animal):
    def __init__(self, name: str, breed: str):
        super().__init__(name, 'Woof')
        self.breed = breed

    def speak(self) -> str:
        return super().speak() + '!'

The instance type determines which implementation runs. Super delegates to the parent implementation.

Generate methods for a data class

python
# Dataclass (Python 3.7+)
from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float
    label: str = ''
    tags: list = field(default_factory=list)

    def distance(self) -> float:
        return (self.x**2 + self.y**2) ** 0.5

The dataclass decorator can generate initialization and representation from declared fields.

Exceptions

Exceptions propagate failures to matching handlers. Catch specific types where recovery is meaningful and use finally or context managers for cleanup.

The else block runs only if the try block finishes without raising. Finally still runs if a handler raises or the function returns. Keep the try block small so the handler covers the operation you intend to recover from.

Handle success and failure paths

python
# try / except / else / finally
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f'Error: {e}')
except (TypeError, ValueError):
    print('Type or value error')
else:
    print('No error:', result)    # runs if no exception
finally:
    print('Always runs')

Else runs on success and finally runs when control leaves the try statement.

Raise errors and release resources

python
# Raise
def divide(a, b):
    if b == 0:
        raise ValueError('Cannot divide by zero')
    return a / b

# Custom exception
class AppError(Exception):
    def __init__(self, message: str, code: int = 0):
        super().__init__(message)
        self.code = code

# Context manager (with statement)
with open('file.txt', 'r') as f:
    content = f.read()
# file is automatically closed

Raise signals a failure. A with block closes the file when execution leaves its body.

File I/O

Files support text or binary I/O. Use with for reliable closing and specify text encodings rather than relying on platform defaults.

Read mode opens existing data. Write mode truncates an existing file, and append mode adds data at the end. Use a scratch directory for examples that write files. A binary file returns bytes, while a text file decodes bytes with its encoding.

Write and read plain text

python
from pathlib import Path

# Write / read
path = Path('output.txt')
path.write_text('Hello, World!', encoding='utf-8')
content = path.read_text(encoding='utf-8')

# Line by line
with path.open(encoding='utf-8') as f:
    for line in f:
        print(line.strip())

Write text with an explicit encoding and iterate over the file for line-by-line processing.

Serialize values and inspect paths

python
import json
from pathlib import Path

# JSON
data = {'name': 'Alice', 'scores': [9, 8, 10]}
json_str = json.dumps(data, indent=2)
parsed  = json.loads(json_str)

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(data, f)

# Path utilities
p = Path('/home/user/docs/file.txt')
p.name         # 'file.txt'
p.stem         # 'file'
p.suffix       # '.txt'
p.parent       # Path('/home/user/docs')
p.exists()
list(Path('.').glob('*.py'))

JSON stores structured values as text. Path methods operate on the file’s location and metadata.

Modules

Modules provide namespaces and normally execute top-level code on their first import in a process. Keep import-time side effects small and group related modules into packages.

The main guard lets a module expose functions on import and run its command-line entry point when executed directly. Treat the package layout and import lines as separate files in the locations indicated by their comments.

Import modules and names

python
import os
import sys
from pathlib import Path
from collections import defaultdict, Counter
from typing import Optional, Union

Import can bind a module or individual names from it in the current namespace.

Use standard library modules

python
# Standard library highlights
import math
math.pi; math.sqrt(2); math.floor(3.7)

import random
random.randint(1, 10)
random.choice(['a', 'b', 'c'])

import datetime
now = datetime.datetime.now()
today = datetime.date.today()

import re
pattern = re.compile(r'\d+')
pattern.findall('abc 123 def 456')   # ['123', '456']
re.sub(r'\s+', ' ', '  hello   world  ')

import itertools
list(itertools.chain([1, 2], [3, 4]))
list(itertools.product('AB', repeat=2))
list(itertools.combinations([1, 2, 3], 2))

Each module groups operations for a domain such as dates or paths.

Generators & Itertools

Generators produce values on demand and retain execution state between yields. They reduce eager storage but are consumed during traversal.

Calling a generator function creates an iterator. The first request runs it to the first yield, and the next request resumes just after that yield. Create a fresh iterator for a second traversal.

See when a generator is exhausted

Read one value explicitly, then collect the remaining values.

python
def counts():
    yield 1
    yield 2

iterator = counts()
print(next(iterator))  # 1
print(list(iterator))  # [2]
print(list(iterator))  # []
print(list(counts()))  # [1, 2]

The first list starts where next left off. The second list is empty because iteration finished. Calling counts again creates a fresh iterator.

Additional examples

Produce and delegate values lazily

python
# Generator function — yields values one at a time
def countdown(n):
    while n > 0:
        yield n
        n -= 1

list(countdown(5))   # [5, 4, 3, 2, 1]

# Generator expression — lazy, no list in memory
squares = (x**2 for x in range(1000))
next(squares)   # 0

# yield from — delegate to a sub-generator
def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

list(flatten([1, [2, [3, 4]], 5]))   # [1, 2, 3, 4, 5]

Yield pauses execution and yield from passes values through from another iterable.

Communicate with a suspended generator

python
# send() / throw() / close() — coroutine-style generator
def accumulator():
    total = 0
    while True:
        value = yield total
        if value is None:
            return
        total += value

gen = accumulator()
next(gen)        # prime the generator → 0
gen.send(10)     # → 10
gen.send(5)      # → 15
gen.close()      # triggers GeneratorExit inside

# itertools
import itertools

list(itertools.chain([1, 2], [3, 4]))              # [1, 2, 3, 4]
list(itertools.product('AB', repeat=2))            # [('A','A'), ('A','B'), ...]
list(itertools.combinations([1, 2, 3], 2))         # [(1,2), (1,3), (2,3)]
list(itertools.permutations([1, 2, 3], 2))         # 6 tuples
list(itertools.islice(itertools.count(1), 5))      # [1, 2, 3, 4, 5]
list(itertools.accumulate([1, 2, 3, 4]))           # [1, 3, 6, 10]
list(itertools.repeat('x', 3))                     # ['x', 'x', 'x']
list(itertools.starmap(pow, [(2, 3), (3, 2)]))     # [8, 9]
for k, g in itertools.groupby([1, 1, 2, 2, 3]):
    print(k, list(g))

Send supplies a value to the suspended yield expression. Close terminates iteration.

Explore more itertools recipes and see how they consume their inputs.

Decorators

Decorators receive a callable or class and return the object bound to its name. Preserve wrapper metadata with functools.wraps so diagnostics and tooling remain useful.

Decoration happens when Python defines the function. The wrapper runs later at each call, forwarding positional and keyword arguments and returning the wrapped result.

Wrap and stack function decorators

Use a wrapper for behavior shared by several functions. The outer wrapper logs once per call and the inner wrapper repeats the greeting three times.

python
import functools

# functools.wraps preserves __name__, __doc__, __annotations__
def log_call(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f'Calling {func.__name__}')
        return func(*args, **kwargs)
    return wrapper

# Decorator factory — decorator that accepts arguments
def repeat(times):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(times): func(*args, **kwargs)
        return wrapper
    return decorator

@log_call
@repeat(3)              # stacked — applied bottom-up
def greet(name): print(f'Hi, {name}!')

greet('Ada')  # Calling greet, then Hi, Ada! three times

Decorate a class

A class decorator receives the class after creation. This example replaces the class name with a callable that reuses the first instance.

python
import functools

# Class decorator — singleton pattern
def singleton(cls):
    _inst = {}
    @functools.wraps(cls)
    def get(*a, **kw):
        if cls not in _inst: _inst[cls] = cls(*a, **kw)
        return _inst[cls]
    return get

@singleton
class Settings:
    pass

print(Settings() is Settings())  # True

Control attribute access and construction

Use a property to validate assignment. A static method needs no instance or class argument. A class method receives the class and can construct a subclass.

python
# @property / @setter / @deleter / @staticmethod / @classmethod
class Circle:
    def __init__(self, r): self._r = r

    @property
    def radius(self): return self._r

    @radius.setter
    def radius(self, v):
        if v < 0: raise ValueError('radius must be >= 0')
        self._r = v

    @radius.deleter
    def radius(self): del self._r

    @staticmethod
    def unit(): return Circle(1)

    @classmethod
    def from_diameter(cls, d): return cls(d / 2)

circle = Circle.from_diameter(6)
circle.radius = 4
print(circle.radius, Circle.unit().radius)  # 4 1
del circle.radius

Cache a computed attribute

Use cached_property when a computed value can be reused. If the underlying data changes, delete the cached attribute to recompute it on the next access.

python
from functools import cached_property

# @cached_property (3.8+) — computed once, then cached as instance attr
class DataSet:
    def __init__(self, data): self.data = data

    @cached_property
    def mean(self): return sum(self.data) / len(self.data)

dataset = DataSet([2, 4])
print(dataset.mean)  # 3.0
dataset.data.append(9)
print(dataset.mean)  # 3.0
del dataset.mean
print(dataset.mean)  # 5.0

Context Managers

Context managers define entry and exit behavior around with blocks. They centralize cleanup for files, locks, transactions, and other scoped resources.

Once entry succeeds, leaving a with block calls the exit method on normal completion or an exception. The exit method can suppress an exception, so that behavior is part of the manager contract.
flowchart TD
    Enter["Enter context"] --> Body["Run with block"]
    Body -->|normal completion| Normal["Exit without exception"]
    Body -->|exception raised| Error["Exit with exception information"]
    Normal --> After["Continue after with"]
    Error --> Choice{"Suppress exception?"}
    Choice -->|yes| After
    Choice -->|no| Propagate["Propagate exception"]

In a generator-based context manager, code before yield prepares the resource. The yielded value becomes the target of as, and a finally block after yield can clean up even if the body raises.

Pair setup with teardown

python
import time
from contextlib import contextmanager, suppress, ExitStack

# __enter__ / __exit__ protocol
class Timer:
    def __enter__(self):
        self._start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed = time.perf_counter() - self._start
        return False   # False → do not suppress exceptions

with Timer() as t:
    sum(range(1_000_000))
print(f'elapsed: {t.elapsed:.4f}s')

# contextlib.contextmanager — generator-based shorthand
@contextmanager
def managed(name):
    print(f'open {name}')
    try:
        yield name
    finally:
        print(f'close {name}')

with managed('db') as conn:
    print(f'using {conn}')

Enter acquires or prepares state and exit handles cleanup when the body finishes.

Compose contexts and await cleanup

python
from contextlib import ExitStack, suppress
# contextlib.suppress — silently swallow specific exceptions
with suppress(FileNotFoundError):
    with open('no-such-file.txt', encoding='utf-8'):
        pass

# ExitStack — dynamic / variable number of context managers
with ExitStack() as stack:
    files = [stack.enter_context(open(f, 'w')) for f in ['a.txt', 'b.txt']]
    # all files closed on exit regardless of exceptions

# Async context manager
class AsyncConn:
    async def __aenter__(self):
        # await self.connect()
        return self

    async def __aexit__(self, *args):
        # await self.disconnect()
        pass

import asyncio
async def use_conn():
    async with AsyncConn() as c:
        pass   # c is connected inside the block

ExitStack manages a dynamic set of contexts. Async context managers can await acquisition and cleanup.

Type Hints & typing

Hints describe expected types to readers and analysis tools. Python does not generally enforce annotations at runtime, so external data still requires validation.

A type variable relates types across parameters and results. A type checker can use the argument to infer the return type, but a caller can still pass unexpected data at runtime.

Describe data and interfaces

python
from typing import (
    Optional, Union, Any, Literal, TypeVar, Generic,
    Protocol, TypedDict, Final, ClassVar, overload,
    TYPE_CHECKING, cast, ParamSpec
)

# Optional / Union — Python 3.10+ prefers X | Y syntax
def find(id: int) -> Optional[str]: ...     # same as str | None
def process(v: Union[int, str]) -> str: ... # same as int | str

# Literal — constrain to exact values
Mode = Literal['r', 'w', 'a']

# TypeVar + Generic
T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None: self._items: list[T] = []
    def push(self, item: T) -> None: self._items.append(item)
    def pop(self) -> T: return self._items.pop()

# Protocol — structural subtyping (duck typing + hints)
class Drawable(Protocol):
    def draw(self) -> None: ...

# TypedDict — typed dict schema
class Movie(TypedDict):
    title: str
    year: int

Generic types carry type arguments. A protocol describes the operations a compatible object supplies.

Express checker-only constraints

python
# Reuse relevant imports or definitions from the preceding example.
# Final / ClassVar
MAX: Final[int] = 1024

class App:
    count: ClassVar[int] = 0

# overload — multiple call signatures, one implementation
@overload
def double(x: int) -> int: ...
@overload
def double(x: str) -> str: ...
def double(x): return x * 2

# TYPE_CHECKING guard — avoids circular imports at runtime
if TYPE_CHECKING:
    from collections.abc import Callable

# cast — tells the checker to trust you (no runtime effect)
raw: Any = '42'
num: int = cast(int, raw)

# ParamSpec (3.10+) — capture parameter types in decorator wrappers
P = ParamSpec('P')

# Self (3.11+) — return type for fluent / builder methods
from typing import Self

class Builder:
    def set_name(self, name: str) -> Self:
        self.name = name
        return self

Overloads describe supported call shapes and casts inform the checker without converting values.

Async / Await

Coroutines cooperate by yielding at await points. Async I/O overlaps waiting, but blocking calls still block the event-loop thread.

Calling an async function creates a coroutine. Await it inside another coroutine or use asyncio.run at a synchronous entry point. Gather lets independent coroutines progress while each waits and returns results in argument order.

Await and gather results

python
import asyncio

async def fetch(url: str) -> str:
    await asyncio.sleep(0.1)   # simulate network I/O
    return f'data from {url}'

# asyncio.run — entry point (starts and stops the event loop)
print(asyncio.run(fetch('https://api.example.com')))

# asyncio.gather — run concurrently, collect all results
async def main():
    a, b, c = await asyncio.gather(
        fetch('https://a.com'),
        fetch('https://b.com'),
        fetch('https://c.com'),
    )
    return a, b, c

print(asyncio.run(main()))

Gather runs awaitables concurrently and returns results in argument order.

Schedule tasks and queue work

python
import asyncio

async def fetch(url: str) -> str:
    await asyncio.sleep(0.1)   # simulate network I/O
    return f'data from {url}'

# asyncio.create_task — schedule without blocking the caller
async def with_tasks():
    t1 = asyncio.create_task(fetch('https://x.com'))
    t2 = asyncio.create_task(fetch('https://y.com'))
    await asyncio.sleep(0)    # yield control; tasks start running
    return await t1, await t2

# asyncio.timeout (Python 3.11+)
async def guarded():
    async with asyncio.timeout(5.0):
        return await fetch('https://slow.example.com')

# asyncio.Queue — producer / consumer pattern
async def producer(q: asyncio.Queue):
    for i in range(5):
        await q.put(i)
        await asyncio.sleep(0.05)
    await q.put(None)   # sentinel to signal done

async def consumer(q: asyncio.Queue):
    while True:
        item = await q.get()
        if item is None:
            break
        print(f'consumed: {item}')

async def pipeline():
    q = asyncio.Queue()
    await asyncio.gather(producer(q), consumer(q))

asyncio.run(pipeline())

A task can run while its caller awaits other work. A queue passes items between producers and consumers.

functools & operator

functools supports wrapping, specialization, and caching, while operator exposes common operations as callables. Cache only when argument-based reuse and retained results suit the function's semantics.

A partial binds some arguments now and accepts the remaining ones later. A cache uses call arguments to find a previous result. If a function depends on changing external state, the saved result can become stale.

Bind arguments ahead of time

Use partial to adapt a general function to a callback that needs fewer arguments.

python
import functools
import operator

# partial — pre-fill arguments to create a new callable
def power(base, exp): return base ** exp

square = functools.partial(power, exp=2)
cube   = functools.partial(power, exp=3)
square(5)   # 25
cube(3)     # 27

print(square(5), cube(3))  # 25 27

Combine values into an accumulator

Use reduce when a binary operation combines the accumulator with each next item. For sums and products, sum and math.prod express the operation directly.

python
import functools
import operator

# reduce — fold a sequence into a single value
functools.reduce(operator.add, [1, 2, 3, 4, 5])     # 15
functools.reduce(operator.mul, range(1, 6))          # 120

print(functools.reduce(operator.mul, range(1, 6)))  # 120

Reuse computed results

Use lru_cache to bound retained entries. Use cache when retaining every distinct call is acceptable. A repeated call with the same arguments can reuse the result.

python
import functools

# lru_cache / cache — memoization
@functools.lru_cache(maxsize=128)
def fib(n: int) -> int:
    return n if n < 2 else fib(n-1) + fib(n-2)

@functools.cache             # Python 3.9+, unbounded
def fact(n: int) -> int:
    return 1 if n == 0 else n * fact(n - 1)

fib.cache_info()             # CacheInfo(hits=..., misses=...)

print(fib(8), fact(5))  # 21 120
hits = fib.cache_info().hits
fib(8)
print(fib.cache_info().hits == hits + 1)  # True

Fill in comparison methods

Use total_ordering when equality and one ordering method already define how instances compare. Here major version takes precedence over minor version.

python
import functools

# total_ordering — supply __eq__ + one comparison, get the rest free
@functools.total_ordering
class Version:
    def __init__(self, major, minor): self.major, self.minor = major, minor
    def __eq__(self, o): return (self.major, self.minor) == (o.major, o.minor)
    def __lt__(self, o): return (self.major, self.minor) < (o.major, o.minor)

print(Version(2, 0) >= Version(1, 9))  # True

Dispatch on the first argument

Use singledispatch when different input types need different implementations behind one function name. An unregistered type falls back to the base implementation.

python
import functools

# singledispatch — function overloading based on argument type
@functools.singledispatch
def process(arg):
    raise TypeError(f'unsupported type: {type(arg).__name__}')

@process.register(int)
def _(arg): return arg * 2

@process.register(str)
def _(arg): return arg.upper()

print(process(3), process('tea'))  # 6 TEA

Build reusable lookup and call functions

Use itemgetter for a key or index, attrgetter for an attribute, and methodcaller to invoke a named method on each object.

python
import operator

# operator module — use in sorted / map / filter instead of lambdas
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
sorted(data, key=operator.itemgetter('age'))
sorted(data, key=operator.itemgetter('name'))

from operator import attrgetter, methodcaller
# sorted(points, key=attrgetter('x'))
# list(map(methodcaller('strip'), lines))

print([row['name'] for row in sorted(data, key=operator.itemgetter('age'))])  # ['Bob', 'Alice']
print(attrgetter('real')(3 + 4j))  # 3.0
print(list(map(methodcaller('strip'), [' tea ', ' coffee '])))  # ['tea', 'coffee']

dataclasses

Dataclasses generate methods from annotated fields. Use default_factory for fresh mutable defaults; frozen instances do not recursively freeze referenced objects.

A default factory runs for each instance that needs a default. That gives each instance its own list. Freezing blocks field assignment, while a list stored in a frozen instance can still be mutated.

Model a record and convert it

Use a dataclass when annotated fields define the data you want to construct, compare, and display. Convert or replace a record with the helpers below.

python
from dataclasses import dataclass
import dataclasses

# @dataclass generates __init__, __repr__, __eq__ automatically
@dataclass
class Point:
    x: float
    y: float
    label: str = ''

# Utility functions
p = Point(3.0, 4.0, 'origin')
dataclasses.asdict(p)           # {'x': 3.0, 'y': 4.0, 'label': 'origin'}
dataclasses.astuple(p)          # (3.0, 4.0, 'origin')
dataclasses.replace(p, x=0.0)  # new Point(0.0, 4.0, 'origin')

print(p == Point(3.0, 4.0, 'origin'))  # True
print(dataclasses.replace(p, x=0.0).x, p.x)  # 0.0 3.0

Initialize per-instance and derived fields

Use a default factory for a fresh list and post-initialization to calculate derived fields. The derived hash stays out of the constructor and representation.

python
from dataclasses import dataclass, field

# field() — customize individual field behavior
@dataclass
class Config:
    host: str = 'localhost'
    port: int = 8080
    tags: list[str] = field(default_factory=list)
    _hash: int = field(default=0, init=False, repr=False)

    def __post_init__(self):   # called after __init__
        self._hash = hash(self.host)

first = Config()
second = Config()
first.tags.append('local')
print(first.tags, second.tags)  # ['local'] []

Freeze fields

Use frozen fields for value-like records. With the default equality settings and hashable fields, a frozen record can be a dictionary key.

python
from dataclasses import dataclass

# frozen=True — immutable and hashable
@dataclass(frozen=True)
class Color:
    r: int; g: int; b: int

hash(Color(255, 0, 0))   # works because frozen

print({Color(255, 0, 0): 'red'}[Color(255, 0, 0)])  # red

Order records by field order

Enable ordering when field declaration order is the comparison order you want.

python
from dataclasses import dataclass

# order=True — auto-generates __lt__, __le__, __gt__, __ge__
@dataclass(order=True)
class Version:
    major: int; minor: int; patch: int

Version(1, 2, 3) < Version(2, 0, 0)   # True

print(Version(1, 2, 3) < Version(2, 0, 0))  # True

Require named arguments and use slots

Use keyword-only fields to make configuration calls explicit. Slots give this class a fixed set of instance attributes.

python
from dataclasses import dataclass

# kw_only=True (3.10+) and slots=True (3.10+)
@dataclass(kw_only=True, slots=True)
class DBConfig:
    host: str
    port: int
    name: str

print(DBConfig(host='localhost', port=5432, name='app').name)  # app

Accept temporary input and share class state

Use InitVar to pass an input to post-initialization without storing it as a dataclass field. ClassVar marks the shared counter.

python
from dataclasses import dataclass, InitVar
from typing import ClassVar

# InitVar — passed to __post_init__, not stored as a field
@dataclass
class Circle:
    radius: float
    diameter: InitVar[float | None] = None
    count: ClassVar[int] = 0

    def __post_init__(self, diameter):
        if diameter is not None: self.radius = diameter / 2
        Circle.count += 1

circle = Circle(radius=0, diameter=10)
print(circle.radius, Circle.count)  # 5.0 1

Metaclasses

Everything in Python is an object — including classes. A metaclass is the class of a class. type is the default metaclass. Custom metaclasses intercept class creation to enforce patterns, register subclasses, or modify attributes. __init_subclass__ is a lighter alternative for most use cases.

Class creation runs once when the class statement executes. Put checks that inspect the namespace there when the rule applies to the class definition itself. Instance initialization runs each time the class is called.

Inspect and create a class with type

Use the one-argument form to inspect an object's type. The three-argument form creates a class from a name, base classes, and a namespace.

python
# Metaclass — the class that creates classes (default: type)
print(type(int))     # <class 'type'>
print(type(list))    # <class 'type'>

# type() can create classes dynamically
Dog = type('Dog', (object,), {'sound': 'woof', 'speak': lambda self: self.sound})
fido = Dog()
print(fido.speak())  # woof

print(type(fido) is Dog, type(Dog) is type)  # True True

Intercept calls to a class

Override the metaclass call method when you need to change what happens each time the class is called. Here the first call initializes an instance and later calls return it again.

python
# Custom metaclass — intercept instance construction
class SingletonMeta(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class Config(metaclass=SingletonMeta):
    def __init__(self):
        self.debug = False

# Both calls return the same object
c1 = Config()
c2 = Config()
assert c1 is c2

c1.debug = True
print(c1 is c2, c2.debug)  # True True

Register subclasses as they are defined

Use the subclass hook when a base class only needs to react to new subclasses. The name supplied in the class header becomes the registry key.

python
# __init_subclass__ — hook called when a class is subclassed (simpler than metaclass)
class Plugin:
    _registry: dict = {}
    def __init_subclass__(cls, name: str = '', **kwargs):
        super().__init_subclass__(**kwargs)
        if name:
            Plugin._registry[name] = cls

class AudioPlugin(Plugin, name='audio'):
    pass

class VideoPlugin(Plugin, name='video'):
    pass

print(Plugin._registry)  # {'audio': AudioPlugin, 'video': VideoPlugin}

print(Plugin._registry['audio'] is AudioPlugin)  # True

Descriptors & Properties

Descriptors are objects that customise attribute access by implementing __get__, __set__, or __delete__. They power property, classmethod, staticmethod, __slots__, and ORM field definitions.

The descriptor object lives on the class. Access through an instance passes that instance to the descriptor, which can validate or transform values while keeping data separate for each object.

Validate attribute access with a descriptor

python
# Descriptor — object that defines __get__, __set__, and/or __delete__
# Used to implement properties, classmethods, staticmethods, slots, etc.

class Validated:
    '''Descriptor that enforces a minimum value.'''
    def __set_name__(self, owner, name):
        self.name = name
        self.private = '_' + name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self   # accessed on the class itself
        return getattr(obj, self.private, 0)

    def __set__(self, obj, value):
        if value < 0:
            raise ValueError(f'{self.name} must be non-negative')
        setattr(obj, self.private, value)

class Circle:
    radius = Validated()
    def __init__(self, r):
        self.radius = r   # calls Validated.__set__

c = Circle(5)
print(c.radius)   # 5
# c.radius = -1  → ValueError

The descriptor intercepts assignment and rejects values outside the accepted range.

Expose managed attributes with property

python
# Reuse relevant imports or definitions from the preceding example.
# property — built-in descriptor shorthand
class Temperature:
    def __init__(self, celsius=0.0):
        self._celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, v):
        if v < -273.15:
            raise ValueError('below absolute zero')
        self._celsius = v

    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32

t = Temperature(100)
print(t.fahrenheit)   # 212.0

A property routes attribute reads and writes through methods.

Protocols & ABCs

Abstract Base Classes enforce an interface through inheritance. Protocols (PEP 544, Python 3.8+) use structural subtyping — any class that implements the required methods satisfies the protocol, without needing to inherit from it. Use @runtime_checkable to enable isinstance checks.

A static type checker compares the required members with the supplied class. A runtime-checkable protocol can check that members exist, but that runtime check does not validate their annotations or signatures.

Declare an abstract base class

python
from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

# Abstract Base Class — enforce interface via inheritance
class Animal(ABC):
    @abstractmethod
    def speak(self) -> str: ...

    @abstractmethod
    def move(self) -> None: ...

class Dog(Animal):
    def speak(self) -> str:  return 'woof'
    def move(self)  -> None: print('run')

Concrete subclasses must implement abstract methods before they can be instantiated.

Describe structural compatibility

python
from typing import Protocol, runtime_checkable

# Protocol (PEP 544) — structural subtyping (duck typing + static checks)
@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> None: ...
    def bounding_box(self) -> tuple[int, int, int, int]: ...

class Circle:   # does NOT inherit Drawable
    def draw(self): print('O')
    def bounding_box(self): return (0, 0, 10, 10)

def render(shape: Drawable) -> None:
    shape.draw()

render(Circle())              # works — Circle structurally matches Drawable
print(isinstance(Circle(), Drawable))  # True (runtime_checkable)

# Built-in ABCs in collections.abc
from collections.abc import Sequence, Mapping, Callable, Iterable

def sum_items(items: Iterable[int]) -> int:
    return sum(items)

sum_items([1, 2, 3])     # list — works
sum_items((1, 2, 3))     # tuple — works
sum_items({1, 2, 3})     # set — works

A protocol accepts a compatible implementation through its methods without requiring inheritance from the protocol.

Multiprocessing & Threading

Threads share memory and can overlap I/O waits. On GIL-enabled CPython, processes can run Python code in parallel because each has its own interpreter. Process startup and serialization add overhead.

Save this example as workers.py and run python workers.py. The main guard keeps child imports from launching more workers. The process pool returns results in input order, and the queue consumer stops when it receives None.

Share state among threads

python
import concurrent.futures
import threading

results = []
lock = threading.Lock()

def record(label):
    with lock:
        results.append(label)

def main():
    thread = threading.Thread(target=record, args=('tea',))
    thread.start()
    thread.join()
    with concurrent.futures.ThreadPoolExecutor() as executor:
        future = executor.submit(record, 'coffee')
        future.result()  # Propagate any worker exception.
    print(results)  # ['tea', 'coffee']

if __name__ == '__main__':
    main()

The lock protects the shared list. Joining or awaiting a future waits for the worker to finish.

Run workers in separate processes

python
import concurrent.futures
import multiprocessing

def sum_squares(n):
    return sum(i * i for i in range(n))

def producer(queue):
    for item in range(3):
        queue.put(item)
    queue.put(None)

def consume(queue):
    items = []
    while (item := queue.get()) is not None:
        items.append(item)
    return items

def main():
    context = multiprocessing.get_context('spawn')
    with context.Pool(processes=2) as pool:
        print(pool.map(sum_squares, [3, 4]))  # [5, 14]

    with concurrent.futures.ProcessPoolExecutor(mp_context=context) as executor:
        print(list(executor.map(sum_squares, [3, 4])))  # [5, 14]

    queue = context.Queue()
    worker = context.Process(target=producer, args=(queue,))
    worker.start()
    print(consume(queue))  # [0, 1, 2]
    worker.join()
    queue.close()

if __name__ == '__main__':
    main()

Spawn imports the worker definitions in child processes. The main guard prevents them from starting another pool on import.

__slots__ & Dunder Methods

__slots__ replaces the per-instance __dict__ with a fixed-size array, reducing memory by ~30–50% for objects with many instances. Dunder methods define how objects behave with built-in operators, functions, and protocols.

A class that declares slots can omit the per-instance dictionary when its inheritance hierarchy permits it. Measure memory in your own workload. Special methods let built-ins such as len or operators delegate to the class implementation.

Limit instance attributes with slots

python
# __slots__ — declare allowed instance attributes to save memory
class Point:
    __slots__ = ('x', 'y')   # no __dict__, ~30% less memory per instance
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
# p.z = 3  → AttributeError — no __dict__

Slots name the permitted instance attributes in this class.

Define behavior for built-in operations

python
# Essential dunder methods
class Vector:
    def __init__(self, x, y): self.x, self.y = x, y

    # Representation
    def __repr__(self):  return f'Vector({self.x}, {self.y})'
    def __str__(self):   return f'({self.x}, {self.y})'

    # Arithmetic operators
    def __add__(self, other): return Vector(self.x + other.x, self.y + other.y)
    def __mul__(self, s):     return Vector(self.x * s, self.y * s)
    def __rmul__(self, s):    return self.__mul__(s)   # s * v

    # Comparison
    def __eq__(self, other):  return self.x == other.x and self.y == other.y
    def __lt__(self, other):  return abs(self) < abs(other)

    # Numeric protocol
    def __abs__(self):       return (self.x**2 + self.y**2) ** 0.5
    def __bool__(self):      return self.x != 0 or self.y != 0
    def __neg__(self):       return Vector(-self.x, -self.y)

    # Container protocol
    def __len__(self):       return 2
    def __getitem__(self, i): return (self.x, self.y)[i]
    def __iter__(self):      return iter((self.x, self.y))

    # Hash — required if __eq__ is defined and object must be hashable
    def __hash__(self):      return hash((self.x, self.y))

v1, v2 = Vector(1, 2), Vector(3, 4)
print(v1 + v2)     # (4, 6)
print(3 * v1)      # (3, 6)
print(abs(v1))     # 2.23...
x, y = v1          # unpacking via __iter__

Special methods let indexing, iteration and operators use the class’s implementation.

itertools & more-itertools

Save any example below as example.py and run python example.py. Comments below print calls show the expected output. The examples use Python 3.10 or later.

Joining and flattening iterables

Use chain when inputs should be read in order as a single stream. Use chain.from_iterable when the inputs themselves arrive in one iterable, such as a sequence of pages. It removes one level of nesting.

python
from itertools import chain
print(list(chain(["draft"], ["review", "publish"])))
# ['draft', 'review', 'publish']
pages = [["A", "B"], [], ["C"]]
print(list(chain.from_iterable(pages)))
# ['A', 'B', 'C']

Pairing inputs and unpacking arguments

Use zip_longest to keep rows from the longer input and fill missing fields. Use starmap when every input tuple already holds the positional arguments for a function. The first tuple below calls pow(2, 3).

python
from itertools import starmap, zip_longest
print(list(zip_longest([1, 2, 3], ["a", "b"], fillvalue="-")))
# [(1, 'a'), (2, 'b'), (3, '-')]
print(list(starmap(pow, [(2, 3), (3, 2)])))
# [8, 9]

Running totals and adjacent pairs

Accumulate emits a result after each input. It adds by default, or uses a supplied function to combine the previous result with the next value. Pairwise, available since Python 3.10, makes overlapping pairs so you can compare adjacent measurements.

python
from itertools import accumulate, pairwise
from operator import mul
print(list(accumulate([2, 3, 4])))
# [2, 5, 9]
print(list(accumulate([2, 3, 4], mul)))
# [2, 6, 24]
print([right - left for left, right in pairwise([18, 21, 20])])
# [3, -1]

Taking a slice from a stream

Islice skips and takes items as it reads the source. Its start is inclusive and its stop is exclusive. Skipped items are consumed too. Count, cycle, and repeat can generate indefinitely, so give islice a finite stop before collecting their output. Repeat also accepts a repeat count.

python
from itertools import count, cycle, islice, repeat
ids = count(10, 2)
print(list(islice(ids, 1, 4)))
# [12, 14, 16]
print(next(ids))
# 18
print(list(islice(cycle(["red", "blue"]), 5)))
# ['red', 'blue', 'red', 'blue', 'red']
print(list(repeat("pending", 3)))
# ['pending', 'pending', 'pending']

Filtering with selectors or predicates

Compress keeps items whose corresponding selector is truthy and stops when either input ends. Filterfalse checks every item and keeps it when the predicate returns false.

python
from itertools import compress, filterfalse
print(list(compress("ABCDE", [1, 0, 1, 0, 1])))
# ['A', 'C', 'E']
print(list(filterfalse(lambda n: n < 5, [1, 3, 5, 2, 7])))
# [5, 7]

Stopping at the first mismatch

Takewhile yields the matching prefix and consumes the first item that fails the predicate. Dropwhile skips that prefix, then yields the first failing item and everything after it. Here the final 2 comes through because dropwhile stops checking once it sees 5.

python
from itertools import dropwhile, takewhile
values = [1, 3, 5, 2]
stream = iter(values)
print(list(takewhile(lambda n: n < 5, stream)))
# [1, 3]
print(next(stream))
# 2
print(list(dropwhile(lambda n: n < 5, values)))
# [5, 2]

Grouping consecutive items

Groupby starts a new group whenever the key changes. Sort by the same key first if rows with equal keys must be grouped together. Each group iterator shares the source with the outer iterator, so consume or save its items before advancing to the next group.

python
from itertools import groupby
from operator import itemgetter
rows = [("a", 2), ("b", 4), ("a", 3)]
key = itemgetter(0)
print([name for name, group in groupby(rows, key=key)])
# ['a', 'b', 'a']
for name, group in groupby(sorted(rows, key=key), key=key):
    print(name, sum(amount for _, amount in group))
# a 5
# b 4

Reading one stream at two speeds

Tee gives two iterators their own positions over a shared source. Continue through the returned iterators after splitting. In this example, tee buffers 10 until the slower reader reaches it. The buffer grows with the distance between readers, so a list may be simpler when one reader finishes a finite stream before the other starts.

python
from itertools import tee
fast, slow = tee(iter([10, 20, 30]))
print(next(fast), next(fast))
# 10 20
print(next(slow))
# 10
print(list(fast), list(slow))
# [30] [20, 30]

Choosing and ordering items

Use product for independent choices at each position. Use combinations for selections where order does not matter, and combinations_with_replacement when a selection may reuse a position. Use permutations for ordered selections without reusing an input position. These tools treat equal values at different input positions as separate choices.

python
from itertools import (
    combinations, combinations_with_replacement, permutations, product,
)
print(list(product("AB", repeat=2)))
# [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
print(list(combinations("AB", 2)))
# [('A', 'B')]
print(list(combinations_with_replacement("AB", 2)))
# [('A', 'A'), ('A', 'B'), ('B', 'B')]
print(list(permutations("AB", 2)))
# [('A', 'B'), ('B', 'A')]

Batches, windows, and single results

Install the optional package with python -m pip install more-itertools. Chunked splits input into nonoverlapping batches and keeps a short final batch. Windowed slides one position at a time. Flatten removes one nesting level. First and last select an endpoint, and one checks that the iterable contains exactly one item.

python
from more_itertools import chunked, first, flatten, last, one, windowed
values = [1, 2, 3, 4, 5]
batches = list(chunked(values, 2))
print(batches)
# [[1, 2], [3, 4], [5]]
print(list(windowed(values, 3)))
# [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
print(list(flatten(batches)))
# [1, 2, 3, 4, 5]
print(first(values), last(values), one(n for n in values if n > 4))
# 1 5 5

pathlib & File System

pathlib.Path (Python 3.4+) replaces os.path string manipulation with an object-oriented API. The / operator builds paths, methods cover reading, writing, globbing, stat queries, and directory creation. shutil handles higher-level operations like copying directory trees, and tempfile provides secure temporary files and directories.

Joining path parts constructs a path without creating files. The filesystem changes only when methods such as mkdir or write_text run. Use an empty scratch directory for the examples that create or copy files.

Compose and inspect paths

python
from pathlib import Path
import shutil, tempfile, os

# Construct paths — platform-independent
base = Path('/home/user/projects')
cfg  = base / 'app' / 'config.toml'   # / operator

# Inspect
cfg.name        # 'config.toml'
cfg.stem        # 'config'
cfg.suffix      # '.toml'
cfg.suffixes    # ['.toml']
cfg.parent      # Path('/home/user/projects/app')
cfg.parts       # ('/', 'home', 'user', 'projects', 'app', 'config.toml')
cfg.is_absolute()

# I/O
p = Path('output.txt')
p.write_text('hello', encoding='utf-8')
p.write_bytes(b'\x00\x01')
content = p.read_text()
raw     = p.read_bytes()

# Filesystem queries
p.exists()
p.is_file()
p.is_dir()
p.stat().st_size      # bytes
p.stat().st_mtime     # modification time

Joining path segments builds a path. File queries inspect the path on disk.

Find and modify files

python
# Reuse relevant imports or definitions from the preceding example.
from pathlib import Path
import os
import shutil
import tempfile

# Create / delete
p.parent.mkdir(parents=True, exist_ok=True)
p.touch()
p.unlink(missing_ok=True)
shutil.rmtree(base, ignore_errors=True)

# Globbing
list(Path('.').glob('*.py'))              # shallow
list(Path('.').rglob('**/*.py'))          # recursive
list(Path('.').glob('test_*.py'))

# Rename / copy
p.rename(p.with_suffix('.bak'))
p.replace(Path('/tmp/file.txt'))          # atomic on same filesystem
shutil.copy2(str(p), '/tmp/')

# Temporary files / dirs
with tempfile.TemporaryDirectory() as td:
    tmp = Path(td) / 'work.txt'
    tmp.write_text('temp data')

# Path from environment variable
home = Path(os.environ.get('HOME', '~')).expanduser()
cfg_dir = Path.home() / '.config' / 'myapp'

Globbing yields matching paths. A temporary directory provides a bounded location for file operations.

Regular Expressions

The re module provides Perl-compatible regular expressions. Compile patterns with re.compile() for reuse. Key operations: search (anywhere), match (start only), fullmatch, findall, finditer, sub, and split. Named groups ((?P<name>...)), lookaheads, and verbose mode (re.VERBOSE) make complex patterns maintainable.

Use fullmatch when the entire input must satisfy the pattern. Search can find a matching substring within otherwise invalid input. A missing match returns None, so check before accessing a group.

Validate the entire input

Use the same pattern to compare finding an order code with validating one.

python
import re

order_code = re.compile(r'ORD-[0-9]{3}')
print(order_code.search('Code: ORD-123').group())  # ORD-123
print(order_code.fullmatch('Code: ORD-123'))       # None
print(bool(order_code.fullmatch('ORD-123')))       # True

Search finds the code inside a longer message. Fullmatch rejects the prefix and accepts the code by itself.

Additional examples

Match text and extract groups

python
import re

# Compile for reuse
pat = re.compile(r'\\d{4}-\\d{2}-\\d{2}')   # ISO date

# search vs match vs fullmatch
re.search(r'\\d+', 'abc 123 def')        # Match at pos 4
re.match(r'\\d+', '123 abc')             # Match only at start
re.fullmatch(r'\\d+', '123')             # Whole string

# findall / finditer
re.findall(r'\\d+', 'a1 b22 c333')       # ['1', '22', '333']
for m in re.finditer(r'\\w+', 'hello world'):
    print(m.group(), m.start(), m.end())

# Groups — numbered, named, non-capturing
m = re.match(r'(?P<year>\\d{4})-(?P<month>\\d{2})', '2024-03')
m.group('year')    # '2024'
m.group(1)         # '2024'
m.groups()         # ('2024', '03')
m.groupdict()      # {'year': '2024', 'month': '03'}

Search can match a substring and fullmatch requires the entire input. Groups expose parts of a match.

Rewrite text and refine patterns

python
import re

# Substitution
re.sub(r'\\s+', ' ', '  hello   world  ')          # 'hello world'
re.sub(r'(\\w+)', r'[\\1]', 'foo bar')             # '[foo] [bar]'
re.subn(r'\\d', '#', 'a1b2c3')                      # ('a#b#c#', 3)

# Split
re.split(r'[,;\\s]+', 'one, two; three  four')     # ['one', 'two', 'three', 'four']

# Flags
re.search(r'hello', 'HELLO', re.IGNORECASE)
re.findall(r'^\\w+', 'line1\nline2', re.MULTILINE)

# Lookahead / lookbehind
re.findall(r'\\w+(?=\'s)', "Alice's cat Bob's dog")  # ['Alice', 'Bob']
re.findall(r'(?<=@)\\w+', 'user@mail.com')            # ['mail']

# Verbose mode for complex patterns
DATE = re.compile(r'''
    (?P<year>  \\d{4}) -   # year
    (?P<month> \\d{2}) -   # month
    (?P<day>   \\d{2})     # day
''', re.VERBOSE)

Sub replaces matches. Flags affect matching and lookarounds constrain a match without consuming characters.

JSON & Serialization

Python offers several serialization formats: json for human-readable interchange, pickle for arbitrary Python objects (binary, Python-only), shelve for a persistent dict backed by pickle, and struct for packing C-style binary data. Custom encoders/decoders extend JSON to handle datetime, dataclass, and other non-default types.

JSON maps interoperable data structures to text. Pickle reconstructs Python objects and can execute code while loading, so use it only with trusted data. The same trust restriction applies to shelve.

Encode and decode JSON

python
import json, pickle, shelve, struct
from dataclasses import dataclass, asdict
from typing import Any

# json.dumps / json.loads — human-readable text
data = {'name': 'Alice', 'scores': [9, 8, 10], 'active': True}
s = json.dumps(data, indent=2, sort_keys=True)
obj = json.loads(s)

# Custom encoder for non-serializable types
import datetime
class DateEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.date):
            return o.isoformat()
        return super().default(o)

json.dumps({'ts': datetime.date.today()}, cls=DateEncoder)

# Custom decoder hook
def decode_hook(d):
    if 'ts' in d:
        d['ts'] = datetime.date.fromisoformat(d['ts'])
    return d

json.loads('{"ts": "2024-01-01"}', object_hook=decode_hook)

Custom hooks convert unsupported Python objects into JSON-compatible values and can reconstruct selected values on decode.

Choose binary or persistent storage

python
# Reuse relevant imports or definitions from the preceding example.
# pickle — binary, Python-only, arbitrary objects
@dataclass
class Model:
    weights: list[float]
    name: str

m = Model([0.1, 0.2, 0.3], 'v1')
blob = pickle.dumps(m, protocol=pickle.HIGHEST_PROTOCOL)
m2   = pickle.loads(blob)

with open('model.pkl', 'wb') as f: pickle.dump(m, f)
with open('model.pkl', 'rb') as f: m3 = pickle.load(f)

# shelve — persistent dict backed by pickle
with shelve.open('store') as db:
    db['model'] = m
    db['config'] = {'lr': 0.01}

with shelve.open('store') as db:
    loaded = db['model']

# struct — pack/unpack C-style binary data
packed = struct.pack('>HH', 1920, 1080)    # big-endian two unsigned shorts
w, h   = struct.unpack('>HH', packed)

# json with dataclasses
@dataclass
class Point:
    x: float
    y: float

p = Point(1.0, 2.0)
json.dumps(asdict(p))   # '{"x": 1.0, "y": 2.0}'

Pickle and shelve require trusted data. Struct instead encodes values according to an explicit binary layout.

Testing with pytest

pytest autodiscovers test files matching test_*.py and rewrites assert statements for rich failure messages. Key features: parametrize for data-driven tests, fixtures for reusable setup/teardown with configurable scope, monkeypatch for environment isolation, tmp_path for temporary files, and marks (skip, xfail) for conditional execution.

Save the examples in a test module and run pytest from the project environment. A parametrized test reports each input separately, and tmp_path gives a test its own temporary directory for file operations.

Parameterize tests and share setup

python
# test_math.py  — run with:  pytest -v
import pytest

# Basic assertions (pytest rewrites assert for rich diffs)
def add(a, b): return a + b

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

# Parametrize — data-driven tests
@pytest.mark.parametrize('a, b, expected', [
    (2, 3, 5),
    (0, 0, 0),
    (-1, 1, 0),
])
def test_add_param(a, b, expected):
    assert add(a, b) == expected

# Fixtures — reusable setup / teardown
@pytest.fixture
def sample_data():
    return [1, 2, 3, 4, 5]

def test_sum(sample_data):
    assert sum(sample_data) == 15

# Fixture with scope
@pytest.fixture(scope='module')
def db_conn():
    conn = {'connected': True}   # simulate DB
    yield conn
    conn['connected'] = False    # teardown

Parametrization runs a case for each input. Fixtures supply reusable test state.

Test failures and isolate side effects

python
import pytest

# Exception testing
def divide(a, b):
    if b == 0: raise ValueError('division by zero')
    return a / b

def test_divide_raises():
    with pytest.raises(ValueError, match='division by zero'):
        divide(1, 0)

# Monkeypatch — replace objects during test
def get_env(key): import os; return os.environ.get(key, '')

def test_env(monkeypatch):
    monkeypatch.setenv('MY_KEY', 'test_value')
    assert get_env('MY_KEY') == 'test_value'

# tmp_path — built-in fixture for temp files
def test_file(tmp_path):
    f = tmp_path / 'data.txt'
    f.write_text('hello')
    assert f.read_text() == 'hello'

# Marks — skip, xfail, custom
@pytest.mark.skip(reason='not implemented yet')
def test_future(): ...

@pytest.mark.xfail(strict=True)
def test_known_bug():
    assert 1 == 2

Raises checks an expected exception. Monkeypatch and tmp_path isolate changes during a test.

Packaging & Virtual Envs

pyproject.toml (PEP 517/518) is the modern standard for declaring build systems, metadata, dependencies, and CLI entry points. Virtual environments isolate project dependencies. uv is a fast Rust-based alternative to pip/venv. Build with python -m build and publish with twine. The __all__ list in __init__.py controls the public API.

Put the TOML declarations in pyproject.toml and the shell commands in a terminal. Activate the virtual environment before installing build tools or running tests so each command uses the intended interpreter and dependencies.

Declare project metadata

python
# pyproject.toml (PEP 517/518) — modern project definition
# [build-system]
# requires = ['setuptools>=68', 'wheel']
# build-backend = 'setuptools.build_meta'
#
# [project]
# name = 'mypackage'
# version = '0.1.0'
# requires-python = '>=3.11'
# dependencies = ['requests>=2.28', 'pydantic>=2']
#
# [project.optional-dependencies]
# dev = ['pytest', 'ruff', 'mypy']
#
# [project.scripts]
# my-cli = 'mypackage.cli:main'

The build-system table selects a backend and project metadata describes dependencies and scripts.

Install and build in an environment

python
# Virtual environments
# python -m venv .venv
# source .venv/bin/activate    (Unix)
# .venv\Scripts\activate       (Windows)
# deactivate

# pip essentials
# pip install -e .              # editable install
# pip install -e '.[dev]'       # with extras
# pip freeze > requirements.txt
# pip install -r requirements.txt

# uv — fast modern package manager
# uv venv
# uv pip install -e '.[dev]'
# uv run pytest

# Building and publishing
# python -m build              # produces dist/*.whl and dist/*.tar.gz
# twine upload dist/*          # to PyPI

# Package structure
# mypackage/
#   __init__.py
#   core.py
#   utils.py
#   py.typed              # marker for PEP 561 (typed package)
# tests/
#   test_core.py
# pyproject.toml
# README.md

# __init__.py — control public API
# from .core import MyClass
# from .utils import helper
# __all__ = ['MyClass', 'helper']

# Namespace packages (no __init__.py needed in PEP 420 style)
# Useful for splitting a package across multiple directories / repos

A virtual environment isolates installed dependencies. An editable install uses the working source tree.

ctypes & C Extensions

ctypes is the standard library's foreign function interface — it loads shared libraries, defines C-compatible types and structures, and calls C functions without writing any C code. For more ergonomic FFI, cffi allows embedding C declarations as strings. Both approaches enable calling platform libraries, wrapping legacy code, or hitting OS APIs directly from Python.

Select a library available on your platform. Set argument and return types to match its declaration before calling a function. A mismatched signature or expired native buffer can crash the process.

Bind a native function signature

python
import ctypes
import ctypes.util

# Load a shared library
libc = ctypes.CDLL(ctypes.util.find_library('c'))

# Call a C function: strlen
libc.strlen.argtypes = [ctypes.c_char_p]
libc.strlen.restype  = ctypes.c_size_t
libc.strlen(b'hello')   # 5

# Fundamental types
ctypes.c_int(42).value
ctypes.c_double(3.14).value
ctypes.c_char_p(b'hi').value

Argument and result declarations tell ctypes how to marshal data for the native call.

Map layouts and pass buffers

python
# Reuse relevant imports or definitions from the preceding example.
import ctypes

# Structures — map to C structs
class Point(ctypes.Structure):
    _fields_ = [('x', ctypes.c_double), ('y', ctypes.c_double)]

p = Point(1.0, 2.0)
p.x   # 1.0

# Arrays
IntArray5 = ctypes.c_int * 5
arr = IntArray5(1, 2, 3, 4, 5)
list(arr)   # [1, 2, 3, 4, 5]

# Pointers
val = ctypes.c_int(10)
ptr = ctypes.pointer(val)
ptr.contents.value   # 10
ptr[0] = 99
val.value            # 99

# Pass a Python buffer (byref / create_string_buffer)
buf = ctypes.create_string_buffer(128)
libc.strcpy(buf, b'hello world')
buf.value   # b'hello world'

# cffi (alternative — more ergonomic)
# from cffi import FFI
# ffi = FFI()
# ffi.cdef('int add(int a, int b);')
# lib = ffi.dlopen('./mylib.so')
# lib.add(2, 3)  # 5

Structure fields must match the native layout. Keep buffers alive while native code uses their addresses.

AST & Code Generation

The ast module parses Python source into an Abstract Syntax Tree, enabling static analysis, linting, code transformation, and metaprogramming. ast.NodeVisitor traverses the tree read-only; ast.NodeTransformer rewrites it in place. After transformation, ast.fix_missing_locations + compile + exec turns the modified AST into running code.

Parsing produces a tree without executing the source. Visit it to inspect nodes or transform it to replace them. Fix location metadata before compiling the transformed tree and execute only code you trust.

Parse and inspect syntax

python
import ast, textwrap

# Parse source into an AST
source = '''
def add(a, b):
    return a + b
result = add(1, 2)
'''

tree = ast.parse(textwrap.dedent(source))

# Walk all nodes
for node in ast.walk(tree):
    if isinstance(node, ast.FunctionDef):
        print('function:', node.name)
    if isinstance(node, ast.Call):
        if isinstance(node.func, ast.Name):
            print('call:', node.func.id)

# Dump the AST (Python 3.8+ indent arg)
print(ast.dump(tree, indent=2))

# NodeVisitor — visitor pattern
class FunctionLister(ast.NodeVisitor):
    def visit_FunctionDef(self, node):
        print(f'def {node.name}({len(node.args.args)} args) at line {node.lineno}')
        self.generic_visit(node)

FunctionLister().visit(tree)

Parse returns a tree. Walking or visiting nodes lets you inspect particular syntax constructs.

Transform and compile a tree

python
import ast

# NodeTransformer — rewrite the AST
class NegateReturns(ast.NodeTransformer):
    def visit_Return(self, node):
        node.value = ast.UnaryOp(op=ast.USub(), operand=node.value)
        return node

new_tree = NegateReturns().visit(ast.parse('def f(): return 42'))
ast.fix_missing_locations(new_tree)
code = compile(new_tree, '<string>', 'exec')
ns = {}
exec(code, ns)
ns['f']()   # -42

# Build an AST from scratch and compile it
body = [ast.Return(value=ast.Constant(value=99))]
func = ast.FunctionDef(
    name='answer', args=ast.arguments(
        posonlyargs=[], args=[], vararg=None, kwonlyargs=[],
        kw_defaults=[], kwarg=None, defaults=[]
    ),
    body=body, decorator_list=[], returns=None
)
mod = ast.Module(body=[func], type_ignores=[])
ast.fix_missing_locations(mod)
exec(compile(mod, '<generated>', 'exec'), ns)
ns['answer']()   # 99

A transformer can replace nodes. Compilation requires a valid tree and source locations on applicable nodes.

Performance & Profiling

Profile before optimising. timeit measures micro-benchmarks; cProfile + pstats reveals function-level hotspots; tracemalloc tracks memory allocations. dis shows compiled bytecode to understand what Python actually executes. Practical optimisations include local variable hoisting, comprehensions over loops, __slots__, functools.cache, and vectorised libraries like NumPy.

Timeit answers how long a small operation takes under repeated trials. A profile shows where a larger workload spends its time. Use an allocation snapshot when the symptom is memory growth and compare equivalent workloads.

Measure elapsed time and call cost

python
import timeit, cProfile, pstats, tracemalloc, sys, dis

# timeit — micro-benchmarks
timeit.timeit('sum(range(1000))', number=10_000)
timeit.timeit(lambda: sum(range(1000)), number=10_000)

# cProfile — function-level profiling
def slow():
    return sum(i**2 for i in range(100_000))

cProfile.run('slow()', sort='cumulative')

# pstats — programmatic access to cProfile output
import io
pr = cProfile.Profile()
pr.enable()
slow()
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats(10)
print(s.getvalue())

Timeit compares small operations. A profiler attributes time to functions in a workload.

Inspect allocations and bytecode

python
import dis
import sys
import tracemalloc

# tracemalloc — memory profiling
tracemalloc.start()
data = [list(range(1000)) for _ in range(100)]
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:3]:
    print(stat)
tracemalloc.stop()

# dis — bytecode inspector (understand what Python compiles to)
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)
dis.dis(fib)

# sys.getsizeof — object memory in bytes
sys.getsizeof([])         # 56
sys.getsizeof(list(range(1000)))  # 8056

# Optimization tips
# 1. Use local variables inside tight loops (faster LOAD_FAST)
# 2. Prefer list comprehensions over append() loops
# 3. Use slots=True on dataclasses / __slots__ for many instances
# 4. numpy / pandas vectorisation beats Python loops by 100x
# 5. functools.cache for expensive pure functions
# 6. Use generators instead of materialising large lists
# 7. Profile first — never optimise without data

Tracemalloc tracks allocations, while dis displays instructions for compiled Python code.

Logging & Configuration

Python's logging module provides a hierarchical logger tree, multiple handlers (stream, file, rotating), formatters, and filters. Always get loggers by logging.getLogger(__name__) so the hierarchy mirrors the package structure. Use logging.config.dictConfig in production for declarative configuration. For structured logging in async web apps, combine contextvars.ContextVar with a custom Filter to attach request IDs to every log line.

A logger creates a record, a handler sends it to a destination, and a formatter controls its appearance. A filter can add a request ID before formatting, so concurrent requests can be traced independently.

Configure application and module loggers

python
import logging
import logging.config
import json, sys
from pathlib import Path

# Basic setup (call once at app entry point)
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler('app.log', encoding='utf-8'),
    ]
)

# Module-level loggers — use __name__ (propagates to root by default)
log = logging.getLogger(__name__)
log.debug('debug message')
log.info('info message')
log.warning('something odd')
log.error('an error occurred')
log.critical('system down')
log.exception('caught exception', exc_info=True)  # includes traceback

A module logger names the source of a record and can propagate it to the application’s handlers.

Configure handlers and structured context

python
import logging
import logging.config
import json
from contextvars import ContextVar

# dictConfig — recommended for production apps
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {'format': '%(asctime)s %(levelname)-8s %(name)s: %(message)s'},
        'json':    {'()': 'logging.Formatter', 'fmt': '%(message)s'},
    },
    'handlers': {
        'console': {'class': 'logging.StreamHandler', 'formatter': 'verbose'},
        'file':    {'class': 'logging.FileHandler', 'filename': 'app.log',
                    'formatter': 'verbose', 'encoding': 'utf-8'},
    },
    'root': {'level': 'INFO', 'handlers': ['console', 'file']},
    'loggers': {
        'myapp.db': {'level': 'WARNING', 'propagate': True},
    },
}
logging.config.dictConfig(LOGGING)

# Structured / JSON logging (manual)
class JSONFormatter(logging.Formatter):
    def format(self, record):
        d = {'ts': self.formatTime(record), 'level': record.levelname,
             'msg': record.getMessage(), 'logger': record.name}
        if record.exc_info:
            d['exc'] = self.formatException(record.exc_info)
        return json.dumps(d)

# contextvar-based request ID (useful in async web servers)
request_id: ContextVar[str] = ContextVar('request_id', default='-')

class RequestFilter(logging.Filter):
    def filter(self, record):
        record.request_id = request_id.get()
        return True

A configuration dictionary wires handlers and formatters. Context variables can associate records with a request.

Best Practices

Writing Pythonic Code

Python rewards idiomatic code — comprehensions, EAFP, built-in iteration helpers, and modern syntax (walrus operator, f-strings, star unpacking) produce shorter, more readable, and often faster programs.

Use a comprehension for a direct transformation or filter. Keep an explicit loop when several state changes or branches need to be understood separately.

Express transformations and iteration directly

python
# Comprehensions over loops
squares = [x**2 for x in range(10)]
evens   = {x for x in range(20) if x % 2 == 0}
index   = {v: i for i, v in enumerate(['a', 'b', 'c'])}

# EAFP (Easier to Ask Forgiveness than Permission)
# Prefer try/except over checking first
try:
    value = my_dict['key']
except KeyError:
    value = 'default'

# Use enumerate(), not range(len())
for i, item in enumerate(['a', 'b', 'c']):
    print(i, item)

# zip() for parallel iteration
for name, score in zip(names, scores):
    print(name, score)

# Throwaway variable
for _ in range(5):
    do_something()

Comprehensions build collections. Enumerate and zip supply the values needed by the loop.

Unpack values and test predicates

python
# Reuse relevant imports or definitions from the preceding example.
# Star unpacking
first, *rest = [1, 2, 3, 4, 5]
head, *middle, tail = range(10)

# Walrus operator := (Python 3.8+)
if (n := len(data)) > 10:
    print(f'too long: {n}')

# any() / all()
all(x > 0 for x in nums)
any(x > 100 for x in nums)

# collections
from collections import defaultdict, Counter, deque
word_count = Counter('banana')        # Counter({'a': 3, 'n': 2, 'b': 1})
graph = defaultdict(list)             # no KeyError on missing key
q = deque([1, 2, 3], maxlen=5)       # O(1) append/pop from both ends

A starred target collects remaining values. Any and all can stop once the result is determined.

Functions & Arguments

Use keyword-only and positional-only parameters to enforce call-site clarity. Annotate all public functions with type hints. Keep functions small and focused, and use functools.cache / lru_cache for expensive pure functions.

A keyword-only parameter makes a call explain an otherwise ambiguous value. Use a fresh mutable object inside the function when each call needs separate state, since a default expression is evaluated at definition time.

Design an explicit signature

python
# Keyword-only args — force callers to name them (after *)
def create_user(name: str, *, admin: bool = False, notify: bool = True):
    pass

create_user('Alice', admin=True)      # OK
# create_user('Alice', True)          # TypeError

# Positional-only args — callers cannot name them (before /)
def parse(text: str, sep: str, /, maxsplit: int = -1) -> list[str]:
    return text.split(sep, maxsplit)

# Type hints on every public function
from typing import Sequence
def average(values: Sequence[float]) -> float:
    return sum(values) / len(values)

# Default args must be immutable — never use mutable defaults
def append_item(item, result=None):   # OK: None, then create list
    if result is None:
        result = []
    result.append(item)
    return result
# def bad(item, result=[]):  WRONG — shared across calls

# Small, focused functions: one task, one level of abstraction
# Use *args/**kwargs sparingly — prefer explicit signatures

Parameter markers control how callers pass arguments. A None sentinel can request a fresh default object.

Cache results and group parameters

python
# Reuse relevant imports or definitions from the preceding example.
# Memoization with functools.cache / lru_cache
from functools import cache, lru_cache

@cache                                # Python 3.9+ unbounded
def fib(n: int) -> int:
    return n if n < 2 else fib(n-1) + fib(n-2)

@lru_cache(maxsize=256)
def expensive(x: int, y: int) -> float: ...

# One-line docstrings for public functions
def greet(name: str) -> str:
    'Return a greeting string for the given name.'
    return f'Hello, {name}!'

# Use dataclasses for parameter groups instead of long arg lists
from dataclasses import dataclass

@dataclass
class QueryOptions:
    limit: int = 100
    offset: int = 0
    order_by: str = 'id'

Cache repeated pure computations when inputs are suitable keys. A data class can name related parameters.

Classes & OOP

Prefer composition over inheritance, use @dataclass for data containers, and __slots__ when creating many instances. Always implement __repr__. Lean on @property and @classmethod over raw getters and imperative constructors.

Composition lets an object delegate work to a collaborator with a focused responsibility. A property can preserve readable attribute access while validating writes, and a class method can express an alternative way to construct the object.

Compose objects and represent state

python
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Protocol

# Prefer composition over inheritance
class Logger:
    def log(self, msg: str) -> None: print(msg)

class Service:
    def __init__(self, logger: Logger) -> None:
        self._logger = logger        # composed, not inherited

# @dataclass for data-holding classes — auto __init__, __repr__, __eq__
@dataclass
class Point:
    x: float
    y: float

# __slots__ for memory-sensitive classes (many instances)
@dataclass(slots=True)              # Python 3.10+
class Particle:
    x: float; y: float; z: float

# Always implement __repr__ for debuggability
class Config:
    def __repr__(self) -> str:
        return f'Config(debug={self.debug!r})'

Composition stores a collaborator. A representation helps identify the state of an instance while debugging.

Provide alternative constructors and properties

python
# Reuse relevant imports or definitions from the preceding example.
# @classmethod for alternative constructors
class Color:
    def __init__(self, r, g, b): self.r, self.g, self.b = r, g, b

    @classmethod
    def from_hex(cls, hex_str: str) -> 'Color':
        h = hex_str.lstrip('#')
        return cls(int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16))

# @property instead of get_/set_ methods
class Circle:
    def __init__(self, radius: float) -> None:
        self._radius = radius

    @property
    def radius(self) -> float:
        return self._radius

    @radius.setter
    def radius(self, value: float) -> None:
        if value < 0: raise ValueError('radius must be non-negative')
        self._radius = value

# Keep __init__ simple — defer heavy work to factory methods or @property
# Use ABCs / Protocols for interfaces, not deep inheritance chains
class Drawable(Protocol):
    def draw(self) -> None: ...

A class method receives the class and can construct it from another input representation.

Error Handling

Be specific in except clauses — never use bare except:. Log with exc_info=True, use contextlib.suppress for ignorable errors, and chain exceptions with raise ... from. Validate only at system boundaries.

Catch failures that the current layer can handle. When translating an exception into a higher-level error, chain it so the caller sees the cause as well as the new context.

Handle and log expected failures

python
import logging
import warnings
from contextlib import suppress

log = logging.getLogger(__name__)

# Be specific in except clauses
try:
    result = risky_op()
except ValueError as exc:
    handle_value_error(exc)
except (TypeError, KeyError) as exc:
    handle_other(exc)

# Never bare except: — catches SystemExit, KeyboardInterrupt, etc.
# BAD:  except:
# GOOD: except Exception:

# Log exceptions with exc_info=True (includes traceback)
try:
    connect()
except ConnectionError as exc:
    log.error('Connection failed', exc_info=True)

# contextlib.suppress for ignorable errors — explicit and readable
with suppress(FileNotFoundError):
    Path('cache.tmp').unlink()

A specific handler limits which failures it intercepts. Logging can attach the traceback.

Preserve causes and express domain errors

python
# Reuse relevant imports or definitions from the preceding example.
# Re-raise with raise...from to preserve the original traceback
try:
    raw = fetch()
except requests.HTTPError as exc:
    raise ServiceError('upstream failed') from exc

# Custom exception hierarchies for domain errors
class AppError(Exception):
    'Base class for all application errors.'

class ValidationError(AppError):
    def __init__(self, field: str, message: str) -> None:
        super().__init__(f'{field}: {message}')
        self.field = field

class NotFoundError(AppError): ...

# Deprecation warnings — use warnings module, not print()
def old_api():
    warnings.warn('old_api() is deprecated, use new_api()', DeprecationWarning, stacklevel=2)

# Validate at system boundaries (input parsing, API responses)
# Do not add defensive checks inside already-trusted internal code

Exception chaining retains the cause when a lower-level failure becomes a domain error.

Tooling & Project Structure

Standardise on pyproject.toml, ruff for linting and formatting, mypy/pyright for type checking, and pytest for tests. Separate src/ from tests/, expose a clean public API via __all__, and use logging instead of print.

Project configuration gives local commands and continuous integration a common source for tool settings. Test the installed package so import behavior matches what downstream users receive.

Configure linting, typing and tests

python
# pyproject.toml — single source of truth for the project
# [project]
# name = 'myapp'
# requires-python = '>=3.11'
# dependencies = ['httpx>=0.27', 'pydantic>=2']
# [project.optional-dependencies]
# dev = ['pytest', 'ruff', 'mypy']

# ruff — fast linter + formatter (replaces flake8 + isort + black)
# ruff check .          lint
# ruff check --fix .    auto-fix safe issues
# ruff format .         format (black-compatible)

# mypy / pyright — static type checking
# mypy src/             check all files under src/
# pyright src/          Microsoft's type checker (used by Pylance)

# pytest — test runner
# pytest -v             verbose output
# pytest -x             stop on first failure
# pytest --cov=src      with coverage (pytest-cov plugin)

Each tool checks a different property, from formatting and types to observed behavior.

Isolate dependencies and organize packages

python
# Virtual environments
# python -m venv .venv
# source .venv/bin/activate   (Unix)
# .venvScriptsactivate      (Windows)

# Pin dependencies for reproducibility
# pip freeze > requirements.txt

# Recommended project layout
# src/
#   myapp/
#     __init__.py        expose public API via __all__
#     core.py
#     utils.py
#     py.typed           PEP 561 marker (package ships type stubs)
# tests/
#   test_core.py
# pyproject.toml

# __all__ — explicit public API, aids IDEs and star-imports
# from .core import MyClass, helper
# __all__ = ['MyClass', 'helper']

# Use logging, not print(), for anything beyond scripts
import logging
log = logging.getLogger(__name__)

# pre-commit hooks — run ruff, mypy, tests before every commit
# .pre-commit-config.yaml  (pip install pre-commit; pre-commit install)

The environment isolates installed packages and a source layout separates package code from tests.

Performance

Profile before optimising with cProfile and timeit. Use generators for large data, sets for O(1) lookup, and local variables in tight loops. Delegate CPU-bound work to multiprocessing, I/O-bound work to asyncio, and numerical work to numpy/pandas.

Compare results and resource usage before and after an optimization. A set helps with repeated membership checks when hashable values are available. A generator helps when the consumer can process values incrementally.

Measure and reduce avoidable work

python
import cProfile, timeit, tracemalloc
from functools import cache

# 1. Profile before optimising — never guess
cProfile.run('my_function()', sort='cumulative')
timeit.timeit('sum(range(1000))', number=10_000)

# 2. Generators for large datasets — no list in memory
def read_lines(path):
    with open(path) as f:
        for line in f:
            yield line.strip()

total = sum(1 for _ in read_lines('big.log'))

# 3. Sets for O(1) membership lookup
valid_ids = {1, 2, 3, 4, 5}
if user_id in valid_ids:      # O(1) vs O(n) for list
    allow()

# 4. Hoist to local variables in tight loops
import math
sqrt = math.sqrt              # avoid repeated attribute lookup
result = [sqrt(x) for x in data]

# 5. Avoid global variables — LOAD_GLOBAL is slower than LOAD_FAST

Profile first. A generator avoids materializing all values and a set supports repeated membership tests.

Choose concurrency and compact representations

python
# Reuse relevant imports or definitions from the preceding example.
# 6. numpy / pandas for numerical work — 100x faster than loops
import numpy as np
arr = np.arange(1_000_000)
arr ** 2                       # vectorised, no Python loop

# 7. multiprocessing for CPU-bound work
from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor() as ex:
    results = list(ex.map(heavy_fn, data))

# 8. asyncio for I/O-bound concurrency
import asyncio
async def fetch_all(urls):
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(u)) for u in urls]
    return [t.result() for t in tasks]

# 9. __slots__ to reduce per-instance memory (~30-50%)
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y): self.x, self.y = x, y

# 10. Built-ins beat manual loops — map/filter/sum/any/all are C-level
total = sum(x**2 for x in range(10_000))   # faster than for-loop accumulate

Processes can run CPU work in parallel. Async tasks can overlap waits, and slots can reduce instance storage.

Diagram
100%