Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Build a TTL Cache Dict in Python
Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.
import time
class TTLDict(dict):
def __init__(self, ttl, *args, **kwargs):
self.ttl = ttl
self._expires = {}
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._expires[key] = time.time() + self.ttl
def __geti…
How to Check SSL Certificate Expiry in Python
Connect to a host over TLS, extract the certificate's expiry date, and report days remaining using only the Python standard library.
import socket
import ssl
from datetime import datetime
def check_cert_expiry(hostname, port=443):
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as tls_sock:
cert = tls_soc…
How to Validate SSL Certificates for Multiple Domains in Python
A Python utility that checks SSL certificate expiry dates for a list of domains using the standard library ssl and socket modules.
import ssl
import socket
from datetime import datetime
def check_ssl_certificate(hostname: str, port: int = 443) -> dict:
"""Validate SSL certificate for a given hostname."""
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=5) as sock:
with context.wra…
How to Implement Probabilistic Early Expiration in Python
A Python mock of probabilistic early expiration for caches, using a heap-based expiry queue and random eviction to approximate cache stampede protection.
import heapq
import random
import time
class ProbabilisticEarlyExpirationMock:
def __init__(self, capacity=1024, expiration_probability=0.1):
self.capacity = capacity
self.expiration_probability = expiration_probability
self._items = {}
self._expiry_heap = []
self._next_id…
How to Implement a Redis-Like Cache Dictionary in Python
Build a RedisMockDict class that mimics basic Redis key-value operations with TTL support, expiry cleanup, and standard dict-like methods.
from collections import OrderedDict
import time
class RedisMockDict:
def __init__(self, ttl=None):
self._data = OrderedDict()
self._ttl = ttl # default TTL in seconds, None = no expiry
self._expiry = {}
def set(self, key, value, ttl=None):
"""Set a key-value pair with optiona…
Implement a TTL cache with a mock clock in Python
This code creates a simple TTL cache that stores values with an expiration timestamp and allows injecting a mock time function to test expiry behavior deterministically.
import time
from functools import wraps
class TTLCache:
def __init__(self, ttl_seconds):
self.ttl = ttl_seconds
self.cache = {}
self._now = time.time
def set_mock_time(self, mock_time_fn):
"""Inject a mock time function for testing TTL expiry."""
self._now = mock_time_…
How to Mock a Redis Session Store in Python
An in-memory RedisSessionStore class with TTL-based expiry, get/set/delete/exists methods, and JSON field support—perfect for testing and prototyping without a live Redis.
import time
import json
from collections import defaultdict
class RedisSessionStore:
"""In-memory mock of a Redis-backed session store."""
def __init__(self, ttl=3600):
self._data = defaultdict(dict)
self._expires = {}
self._ttl = ttl
def set(self, session_id, field, value):
…
Mock client credentials machine auth in Python
This code simulates the OAuth2 client-credentials flow for service-to-service calls, generating a mock bearer token with expiry and caching, plus a revoke method, using only the standard library.
import time
import hashlib
import secrets
class MachineAuth:
"""Mock client-credentials machine auth for service-to-service calls."""
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
self._token = None
self._expire…
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.