Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Sort Command-Line Arguments in Python
Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.
import argparse
def main():
parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
args =…
How to validate argparse CLI commands in Python
Build a beginner-friendly command-line argument parser with argparse, including required and optional arguments, plus simple validation for age.
import argparse
def main():
parser = argparse.ArgumentParser(description="Validate CLI arguments for beginners.")
parser.add_argument("name", type=str, help="Your name.")
parser.add_argument("--age", type=int, default=None, help="Your age (optional).")
parser.add_argument("--verbose", action="store_t…
How to Use multiprocessing Pool map and starmap in Python
Parallelize functions over iterables with Pool.map, and unpack multiple arguments via Pool.starmap.
from multiprocessing import Pool
def square(x):
return x * x
def add_and_multiply(a, b, c):
return (a + b) * c
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
with Pool(processes=2) as pool:
squares = pool.map(square, numbers)
print(f"squares: {squares}")
starmap_arg…
How to Mock an Object Method in Python unittest
Mock a method on an instance or class with @patch.object, set its return value, and assert its call arguments in Python unittest.
import unittest
from unittest.mock import patch
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
class TestCalculator(unittest.TestCase):
def test_add_normal(self):
calc = Calculator()
result = calc.add(2, 3)
self.asse…
How to Use mock.assert_called_with in Python
Verify that a MagicMock received a call with specific positional and keyword arguments using assert_called_with in unittest.
import unittest
from unittest.mock import MagicMock
class TestMockAssertions(unittest.TestCase):
def test_assert_called_with(self):
# Create a mock object
mock = MagicMock()
# Call the mock with specific arguments
mock.send_email("alice@example.com", subject="Greetings", body="Hel…
How to Build a Sidecar Logging Proxy in Python
Wrap any object with a proxy that transparently logs every method call, arguments, return value, and execution time to a file — mimicking a sidecar pattern.
import logging
import time
from datetime import datetime
class LoggingProxy:
"""Sidecar-style proxy that logs all calls to a wrapped object."""
def __init__(self, target, log_file="proxy.log"):
self._target = target
logging.basicConfig(
filename=log_file,
level=loggin…
At Most Once Fire-and-Forget Mock in Python
A Python mock that enforces send() is called at most once and records the arguments for verification.
class FireForgetMock:
def __init__(self):
self._calls = 0
self._last_args = None
self._last_kwargs = None
def send(self, *args, **kwargs):
if self._calls > 0:
raise RuntimeError("send() called more than once")
self._calls += 1
self._last_args = args
…
How to create a stable cache key from function arguments in Python
Generate a stable SHA-256 cache key from normalized function arguments, with keyword order normalized and tests using mocks.
import hashlib
import json
from unittest.mock import Mock
def make_cache_key(*args, **kwargs):
"""Normalize args/kwargs into a stable hash key for caching."""
normalized = {
"args": [repr(arg) for arg in args],
"kwargs": {key: repr(value) for key, value in sorted(kwargs.items())}
}
pa…
Mocking a Metrics Gauge's set_value Method in Python
Demonstrates using unittest.mock.Mock with wraps to intercept a gauge's set_value call while verifying arguments and preserving real behavior.
from unittest.mock import Mock
class MetricsGauge:
def __init__(self, name):
self.name = name
self.value = 0.0
def set_value(self, new_value):
self.value = float(new_value)
return self.value
# Usage demonstration with a mock
gauge = MetricsGauge("cpu_usage")
gauge_mock = Mock…
How to Mock a Function Call in Python with unittest.mock
Use unittest.mock.Mock to wrap a function and spy on its call count and arguments in Python.
import random
from unittest.mock import Mock, patch
def select_n_plus_one(numbers: list[int]) -> int:
"""Return the first number that appears more than once, if any."""
seen = set()
for num in numbers:
if num in seen:
return num
seen.add(num)
return -1
def detect_mock(se…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.