Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Build a Python Tool That Finds Trending Open Source Projects Daily
A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.
import requests
import json
import datetime
def fetch_trending_projects(language: str = "", since: str = "daily"):
url = "https://api.github.com/search/repositories"
date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
query = f"created:>{date_limit} language:{language}" if langua…
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 Implement Retry with Exponential Backoff and Jitter in Python
This code demonstrates a retry mechanism with exponential backoff and optional full jitter, using a flaky mock network call for testing.
import random
import time
def retry_with_backoff(func, max_attempts=5, base_delay=0.1, jitter=True):
"""
Retry a function with exponential backoff and optional full jitter.
"""
for attempt in range(max_attempts):
try:
return func()
except Exception as e:
if att…
How to Cache Function Results in Redis with Python
A Python decorator that caches function results in Redis using TTL, with optional fakeredis for testing without a server.
import redis
import json
import time
try:
import fakeredis
except ImportError:
fakeredis = None
from functools import wraps
def cache_redis(cache_key_prefix="cache", ttl=60):
"""Decorator to cache function results in Redis."""
if fakeredis:
r = fakeredis.FakeStrictRedis()
else:
r…
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.