Testing & modern typing
pytest basics, mocks, type hints, TypedDict, Protocol, and static-checking patterns.
How to Compare Execution Speed Between Python Functions
Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.
import time
import random
def method_a(values):
"""Sort using built-in sorted."""
return sorted(values)
def method_b(values):
"""Sort using list's sort method."""
values_copy = values[:]
values_copy.sort()
return values_copy
def method_c(values):
"""Sort manually using bubble sort (slow,…
How to Validate Data in Python with Typing Hints
Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.
from typing import Any, Optional, Union, TypeVar, get_origin, get_args
T = TypeVar("T")
def validate(value: Any, expected_type: type) -> Optional[str]:
"""Returns an error message if value doesn't match expected_type, else None."""
# Handle Optional[...] types
origin = get_origin(expected_type)
if or…
How to freeze time in Python tests with freezegun
Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.
from datetime import datetime
from freezegun import freeze_time
@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
now = datetime.now()
return now
if __name__ == "__main__":
result = test_frozen_time()
print(result)
Mock datetime with time-machine in Python
Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().
from time_machine import travel
from datetime import datetime
@travel("2020-01-01 10:30:00")
def check_date():
return datetime.utcnow()
if __name__ == "__main__":
print(check_date())
Mock datetime.now to freeze time in Python
Use unittest.mock.patch to replace datetime.now with a fixed value so your code always sees the same time during tests.
from datetime import datetime
from unittest.mock import patch
def current_message():
now = datetime.now()
return f"Current time: {now:%Y-%m-%d %H:%M:%S}"
if __name__ == "__main__":
with patch("__main__.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2024, 3, 15, 10, 30, 0)
prin…
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.