Reference library

Testing & modern typing

pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.

2 matches
Testing & modern typing easy

Dataclass with Type Hints Fields in Python

Create a data class with typed fields and default values, then instantiate and inspect it.

dataclass type hints oop
Python
from dataclasses import dataclass


@dataclass
class Person:
    name: str
    age: int
    email: str = "unknown@example.com"
    is_active: bool = True


if __name__ == "__main__":
    person = Person(name="Alice", age=30)
    print(person)
    print(f"Name: {person.name}, Age: {person.age}, Email: {person.email}, A…
13 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…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Testing & modern typing — Python code examples

What you will find here

This page collects testing & modern typing snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.