Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

25 matches
Errors & debugging easy

How to Test Exceptions in Python with pytest.raises

Learn the pytest.raises pattern to assert that specific exceptions are raised and validate their messages.

pytest testing exceptions
Python
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b


def test_divide_by_zero_raises():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)


def test_divide_by_zero_raises_exact_match():
    with py…
14 0 Open
Automation & scripting easy

Run pytest and email summary in Python

Runs pytest via subprocess, extracts the test summary line, and sends it in an email (mocked for demonstration).

pytest subprocess email
Python
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def run_tests():
    """Run pytest and capture the summary output."""
    result = subprocess.run(
        ["pytest", "-q"],
        capture_output=True,
        text=True
    )
    return result.stdo…
12 0 Open
Data pipelines & processing easy

Test a Python Pipeline with Fixture Sample Rows

Test pipeline functions with sample rows provided by a pytest fixture, verifying required keys and value constraints.

pytest fixtures data-pipelines
Python
import pytest


def get_value(data: dict, key: str):
    return data.get(key)


def sample_rows():
    return [
        {"name": "Alice", "age": 30, "city": "London"},
        {"name": "Bob", "age": 25, "city": "Paris"},
        {"name": "Charlie", "age": 35, "city": "Berlin"},
    ]


@pytest.fixture
def sample_data(…
15 0 Open
Modern tooling easy

How to Define Nox Sessions in Python

Automate repetitive tasks like testing and linting with reusable Nox sessions.

nox automation task-runner
Python
import nox


@nox.session(python=["3.9", "3.10"])
def tests(session):
    session.install("pytest")
    session.run("pytest")


@nox.session(python="3.9")
def lint(session):
    session.install("ruff")
    session.run("ruff", "check", ".")


if __name__ == "__main__":
    print("Nox sessions defined: tests, lint")
   …
13 0 Open
Modern tooling easy

How to Parametrize Tests in Python with pytest

This code demonstrates how to use pytest's @pytest.mark.parametrize decorator to run a single test function against multiple input sets, ensuring comprehensive coverage with minimal code duplication.

pytest parametrize testing
Python
import pytest


def multiply(a, b):
    return a * b


@pytest.mark.parametrize("x, y, expected", [
    (2, 3, 6),
    (4, 5, 20),
    (0, 10, 0),
    (7, 1, 7),
])
def test_multiply(x, y, expected):
    result = multiply(x, y)
    assert result == expected, f"multiply({x}, {y}) = {result}, expected {expected}"


if _…
14 0 Open
Modern tooling easy

How to Use pytest Fixtures and conftest.py for Shared Setup in Python

Learn how to define reusable pytest fixtures for shared setup and use them to keep tests clean and maintainable.

pytest fixtures conftest
Python
import pytest

class Calculator:
    def add(self, a, b):
        return a + b

    def multiply(self, a, b):
        return a * b


@pytest.fixture
def calc():
    return Calculator()


@pytest.fixture
def sample_numbers():
    return (3, 5)


def test_add(calc, sample_numbers):
    a, b = sample_numbers
    assert c…
12 0 Open
Modern tooling easy

pytest mark slow skip integration

Uses pytest markers to select fast tests, skip unfinished ones, and run integration checks with verbose output.

pytest markers testing
Python
import pytest

def test_fast():
    assert 1 + 1 == 2

@pytest.mark.slow
def test_slow():
    import time
    time.sleep(1)
    assert 5 * 5 == 25

@pytest.mark.skip(reason="Not ready for production")
def test_skipped():
    assert 2 + 2 == 5

@pytest.mark.integration
def test_integration():
    database = {"users": […
16 0 Open
Testing & modern typing easy

Capture stdout and stderr with pytest capsys

Use pytest's capsys fixture to capture and assert on standard output and error streams in your tests.

pytest testing capture
Python
import pytest

# Function under test
def greet(name):
    print(f"Hello, {name}!")
    print(f"Error: {name} not found", file=sys.stderr)

def test_captures_stdout_and_stderr(capsys):
    greet("Alice")
    captured = capsys.readouterr()
    
    assert "Hello, Alice!" in captured.out
    assert "Error: Alice not foun…
12 0 Open
Testing & modern typing easy

How to Assert Exceptions in Python with pytest.raises

Use pytest.raises as a context manager to assert that a function raises an expected exception and inspect its message in pytest tests.

pytest testing exceptions
Python
import pytest

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

def test_divide_by_zero():
    with pytest.raises(ValueError) as exc_info:
        divide(10, 0)
    assert str(exc_info.value) == "Cannot divide by zero"
    assert "zero" in str(exc_info.value)

def te…
13 0 Open
Testing & modern typing medium

How to Benchmark Python Code with pytest-benchmark and mocks

Use pytest-benchmark to measure function performance while combining Mock and patch for controlled test scenarios.

pytest benchmark mock
Python
import time
from unittest.mock import Mock, patch

import pytest
from pytest_benchmark.fixture import BenchmarkFixture


def heavy_operation(data: list[int]) -> int:
    """Simulates a CPU-bound operation."""
    return sum(x * x for x in data)


def test_heavy_operation_benchmark(benchmark: BenchmarkFixture) -> None:…
13 0 Open
Testing & modern typing easy

How to Capture Logging Records with pytest caplog in Python

Capture and assert on logging records in pytest using the built-in caplog fixture.

pytest logging testing
Python
import logging
import pytest

def divide(a, b):
    """Divide two numbers and log an error if b is zero."""
    if b == 0:
        logging.error("Division by zero attempted")
        return None
    logging.info(f"Dividing {a} by {b}")
    return a / b

def test_divide_logs_error(caplog):
    with caplog.at_level(logg…
13 0 Open
Testing & modern typing easy

How to Compare Floats in pytest with approx

Uses pytest.approx to compare floating-point numbers with tolerance, avoiding precision issues.

pytest floating-point testing
Python
import pytest

def test_float_addition():
    result = 0.1 + 0.2
    expected = 0.3
    assert result == pytest.approx(expected)
12 0 Open
Testing & modern typing medium

How to Mock a Factory Boy Model Instance in Python

Create a factory boy factory, then patch its Meta.model with a Mock to control instance behavior in tests.

factory-boy mocking unit-testing
Python
import factory
from dataclasses import dataclass
from unittest.mock import Mock, patch
import builtins


@dataclass
class User:
    name: str
    age: int


class UserFactory(factory.Factory):
    class Meta:
        model = User

    name = "Alice"
    age = 30


def get_user_name(user):
    return user.name


def ma…
14 0 Open
Testing & modern typing easy

How to Parametrize pytest Tests with Multiple Input Cases in Python

This code shows how to use pytest's @pytest.mark.parametrize decorator to run the same test function across multiple input-output combinations, checking that an add function behaves correctly for each case.

pytest parametrize testing
Python
import pytest

def add(a, b):
    return a + b


@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (5, 5, 10),
    (-1, 1, 0),
    (0, 0, 0),
    (10, -3, 7),
])
def test_add(a, b, expected):
    assert add(a, b) == expected


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
13 0 Open
Testing & modern typing medium

How to Run Test Coverage with pytest-cov in Python

Run pytest with coverage reporting using pytest-cov on a temporary project and see line-by-line coverage output.

pytest coverage testing
Python
import os
import subprocess
import tempfile
from pathlib import Path


def sample_function(x: int) -> int:
    """A simple function to demonstrate coverage."""
    if x > 0:
        return x * 2
    else:
        return -x


def run_pytest_with_coverage() -> str:
    """Run pytest with coverage on a temp project and r…
13 0 Open
Testing & modern typing easy

How to Share Fixtures Across Tests with pytest conftest

Learn how to define pytest fixtures in conftest.py and control their scope (function, module, session) so every test in a directory reuses the same setup and teardown.

pytest fixtures conftest
Python
import pytest

@pytest.fixture
def sample_data():
    """Simple fixture available to all tests in this directory."""
    return {"name": "Alice", "age": 30}

@pytest.fixture(scope="session")
def session_data():
    """Fixture created once per test session."""
    return {"session_id": 12345}

@pytest.fixture(scope="mo…
12 0 Open
Testing & modern typing easy

How to Skip Slow Tests with pytest.mark in Python

Use pytest.mark.skip and custom marks like @pytest.mark.slow to skip or deselect slow tests during test runs.

pytest testing skip
Python
import pytest
import time


def test_fast():
    assert 1 + 1 == 2


@pytest.mark.skip(reason="slow test skipped by default")
def test_slow():
    time.sleep(5)
    assert True


@pytest.mark.slow
def test_marked_slow():
    time.sleep(5)
    assert True


if __name__ == "__main__":
    pytest.main([__file__, "-v", "-…
11 0 Open
Testing & modern typing medium

How to Snapshot Test JSON with Mock in Python

Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.

pytest snapshot mock
Python
import json
from unittest.mock import Mock, patch
import pytest


def load_config(data):
    config = json.loads(data)
    return {"host": config["host"], "port": config["port"]}


def test_load_config_snapshot(snapshot):
    mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
    result = …
13 0 Open
Testing & modern typing easy

How to Test Environment Variables with pytest monkeypatch in Python

Shows how to use pytest's monkeypatch fixture to set and delete environment variables for isolated tests.

pytest monkeypatch environment variables
Python
import os
import pytest

def get_database_url():
    return os.getenv("DATABASE_URL", "postgres://default")

def test_database_url_with_env(monkeypatch):
    monkeypatch.setenv("DATABASE_URL", "postgres://test-db")
    assert get_database_url() == "postgres://test-db"

def test_database_url_default(monkeypatch):
    m…
11 0 Open
Testing & modern typing easy

How to Use the pytest tmp_path Fixture for Temporary Directories

Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.

pytest tmp_path fixtures
Python
import pytest


def test_write_and_read_file(tmp_path):
    # tmp_path is a pytest fixture that provides a temporary directory
    # unique to each test invocation
    data_file = tmp_path / "data.txt"
    data_file.write_text("hello world")
    assert data_file.read_text() == "hello world"


def test_multiple_tmp_pat…
12 0 Open
Testing & modern typing easy

How to Write a pytest Test Function with assert Equal in Python

Define simple pytest test functions that use assert to verify result equality and run them with pytest.main.

pytest unit testing assert
Python
import pytest

def add(a, b):
    return a + b

def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5

def test_add_negative_numbers():
    result = add(-2, -3)
    assert result == -5

def test_add_mixed_numbers():
    result = add(2, -3)
    assert result == -1

if __name__ == "__main__":
  …
10 0 Open
Testing & modern typing easy

How to Write pytest Test Function Assert Equal in Python

Write three pytest test functions that assert the result of an add() function equals an expected numeric value.

pytest assert testing
Python
import pytest

def add(a, b):
    return a + b

def test_add_positive_numbers():
    assert add(2, 3) == 5

def test_add_negative_numbers():
    assert add(-1, -2) == -3

def test_add_mixed_numbers():
    assert add(5, -3) == 2

if __name__ == "__main__":
    pytest.main([__file__, "-v"])
11 0 Open
Testing & modern typing easy

How to mark known bugs with pytest xfail in Python

Use @pytest.mark.xfail to mark tests that are expected to fail due to known bugs, with optional strict mode to control pass/fail behavior.

pytest testing xfail
Python
import pytest


def divide(a: int, b: int) -> float:
    if b == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return a / b


@pytest.mark.xfail(reason="Known bug: division returns int instead of float", strict=False)
def test_divide_integer_division():
    result = divide(10, 4)
    assert isinstanc…
15 0 Open
Testing & modern typing medium

Use pytest fixture to mock a database connection in Python

This code shows how to use a pytest fixture and unittest.mock to replace a database connection with a Mock, enabling isolated tests without a real database.

pytest fixtures unittest.mock
Python
import pytest
import sqlite3
from unittest.mock import Mock

class Database:
    def __init__(self, connection):
        self.connection = connection

    def get_user(self, user_id):
        cursor = self.connection.cursor()
        cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
        return cursor.…
18 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.