Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to define an exception hierarchy for domain errors in Python
Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.
class DomainError(Exception):
"""Base class for all domain errors."""
pass
class ValidationError(DomainError):
"""Raised when input data fails validation rules."""
pass
class NotFoundError(DomainError):
"""Raised when a requested entity does not exist."""
pass
class PermissionDeniedError(Dom…
How to handle ZeroDivisionError in Python
Wrap a division operation in try/except to return None or a friendly message instead of crashing when dividing by zero.
def safe_divide(a, b):
"""Return a/b if possible, else None when dividing by zero."""
try:
return a / b
except ZeroDivisionError:
return None
def safe_divide_with_message(a, b):
"""Return a how-to message on divide-by-zero error."""
try:
return a / b
except ZeroDivisio…
How to parse a traceback to get the last frame in Python
Extracts the innermost frame's file, line, and function name from a Python traceback object.
import sys
import traceback
def parse_traceback_last_frame(exc_info):
"""Return the file, line, and function of the last (innermost) frame."""
_, _, tb = exc_info
last_tb = tb
while last_tb.tb_next is not None:
last_tb = last_tb.tb_next
filename = last_tb.tb_frame.f_code.co_filename
l…
Implement a Context Manager That Suppresses Exceptions in Python
Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.
import contextlib
class SuppressExceptions:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return False
if not self.exceptions or exc_type in se…
Map Exception Type to HTTP Status Code in Python
Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.
EXCEPTION_STATUS_MAP = {
ValueError: 400,
KeyError: 400,
TypeError: 400,
PermissionError: 403,
FileNotFoundError: 404,
AttributeError: 404,
TimeoutError: 408,
NotImplementedError: 501,
ConnectionError: 503,
}
def status_code_for(exception_type):
try:
return EXCEPTION_S…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
Try Except ValueError in Python: Handle Conversion Errors
Catch ValueError exceptions when converting strings to integers or performing arithmetic, returning None on failure instead of crashing.
def convert_to_int(value):
try:
return int(value)
except ValueError as error:
print(f"Conversion failed: {error}")
print(f"Problem value was: {repr(value)}")
return None
def divide_numbers(numerator, denominator):
try:
result = numerator / denominator
retur…
Validate try except ValueError handler for beginners — errors debugging
Learn how to validate user input and handle division errors safely using try/except with ValueError and ZeroDivisionError in Python.
def divide_numbers(a, b):
"""Divide two numbers, catching division by zero and value errors."""
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError:
print("Error: Both arguments must be numbers!")
retu…
How to define a custom exception class in Python with an error code attribute
Create a custom exception class with extra attributes like an error code, then raise and catch it in a try/except block.
class UserNotFoundError(Exception):
def __init__(self, user_id, error_code=404):
self.user_id = user_id
self.error_code = error_code
super().__init__(f"User with ID {user_id} was not found (error code: {error_code})")
def find_user(user_id, users_db):
if user_id not in users_db:
…
How to Close a Generator and Handle GeneratorExit in Python
This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.
def countdown(n):
try:
while n > 0:
yield n
n -= 1
finally:
print(f"Generator closed after countdown completed")
if __name__ == "__main__":
gen = countdown(5)
print(next(gen))
print(next(gen))
gen.close()
print("Generator closed explicitly")
How to Throw an Exception into a Python Generator
This code demonstrates how to use the .throw() method on a generator to inject an exception at its current yield point and let it recover gracefully.
def demo_throw_into_generator():
"""Demonstrate throwing an exception into a running generator."""
def counter():
"""Generator that counts until interrupted."""
try:
i = 0
while True:
yield i
i += 1
except ValueError as e:
…
How to Cross Post Markdown to dev.to API in Python
A Python function that POSTs markdown content to the dev.to API and handles HTTP or URLError exceptions with mock API testing.
import json
from urllib import request, error
def cross_post_to_devto(markdown_content, api_key, devto_api_url="https://dev.to/api/articles"):
"""
Mock cross-posting of markdown content to the dev.to API.
Returns the API response or an error message.
"""
payload = json.dumps({
"article": …
Python Exponential Backoff Retry Example
Retry a flaky function with exponential backoff and jitter-free delays, printing each attempt and finally returning the successful result.
import random
import time
def flaky_function():
if random.random() < 0.6:
raise ConnectionError("Temporary network error")
return "success"
def retry_with_exponential_backoff(func, max_retries=5, base_delay=1.0):
for attempt in range(max_retries + 1):
try:
return func()
…
Graceful Shutdown Executor Context Manager in Python
A context manager that starts a background thread and ensures it stops gracefully on exit, handling timeouts and exceptions.
import signal
import threading
import time
from contextlib import contextmanager
@contextmanager
def graceful_shutdown_executor(timeout=5.0):
"""Context manager that runs a task and gracefully stops it on timeout or exception."""
stop_event = threading.Event()
def task():
print("Task started")
…
Fuzz Test Random Bytes Input Crash in Python
A simple fuzz test generates random byte inputs and runs a parser to find unexpected crashes.
import random
def parse_header(data: bytes) -> dict:
"""Parse a fake binary header format."""
if len(data) < 8:
raise ValueError("header too short")
magic = data[:4]
if magic != b'PARS':
raise ValueError("bad magic")
version = data[4]
if version != 1:
raise ValueErro…
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.
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…
How to use unittest mock side_effect with a sequence in Python
Demonstrates using Mock.side_effect with a list to return different values per call and raise an exception at a specific call in unittest.
import unittest
from unittest.mock import Mock
class TestMockSideEffectSequence(unittest.TestCase):
def test_side_effect_sequence(self):
mock = Mock()
mock.side_effect = [1, 2, 3, Exception("boom")]
self.assertEqual(mock(), 1)
self.assertEqual(mock(), 2)
self.asser…
How to Retry on Specific Exception Tuples in Python
A decorator-based retry pattern that retries a function only when it raises exceptions specified in a tuple, with configurable retries and delay.
import time
import random
from unittest.mock import patch
def retry_on_exceptions(retries=3, exceptions=(ValueError,), delay=0.1):
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(retries):
try:
return func(*args, **kwargs)
…
How to retry idempotent operations with a mock in Python
Wrap a flaky idempotent operation in a retry loop with exponential backoff, and use unittest.mock to deterministically test the str's behavior.
import random
import time
from unittest.mock import Mock
def idempotent_operation(value):
"""Simulate an idempotent operation that sometimes fails."""
if random.random() < 0.6: # 60% failure rate
raise ConnectionError("Temporary failure")
return value * 2
def retry_with_backoff(operation, max_…
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.