Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Load Pickle Files Safely in Python
This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.
import pickle
# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
def __reduce__(self):
return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))
# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())
# Safe ap…
How to Load and Save JSON Files in Python
Load and save JSON files with pretty formatting using Python's standard library json module and pathlib.
import json
from pathlib import Path
def load_json(filepath: str) -> dict:
"""Load JSON data from a file."""
path = Path(filepath)
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def save_json(filepath: str, data: dict) -> None:
"""Save data to a JSON file with pretty format…
How to Serialize a Python Object to Pickle Bytes in Memory
Serialize a Python object to pickle bytes in memory with pickle.dumps, then deserialize it back with pickle.loads and verify the roundtrip.
import pickle
class Person:
def __init__(self, name, age, skills):
self.name = name
self.age = age
self.skills = skills
def main():
person = Person("Alice", 30, ["Python", "SQL", "Docker"])
# Serialize to bytes in memory
pickle_bytes = pickle.dumps(person)
print(…
How to Write Simple XML Documents with ElementTree in Python
Create well-structured XML documents in memory using Python's built-in ElementTree module, complete with nested elements, attributes, and text content.
import xml.etree.ElementTree as ET
def create_xml_document():
# Create root element
root = ET.Element("catalog")
# Create a book element with attributes and children
book1 = ET.SubElement(root, "book", id="bk101")
ET.SubElement(book1, "author").text = "Gambardella, Matthew"
ET.SubElement(…
How to Write a Dict to a Pretty JSON File with Indent in Python
Serializes a Python dictionary to a readable JSON file using json.dump with indentation and sorted keys, then prints the file contents to stdout.
import json
from pathlib import Path
data = {
"name": "Python",
"version": 3.12,
"features": ["simple", "readable", "powerful"],
"nested": {"creator": "Guido van Rossum", "year": 1991}
}
output_path = Path("output.json")
with output_path.open("w", encoding="utf-8") as f:
json.dump(data, f, inden…
How to Pickle a Python Dict and Load It Back
Save a dictionary to a binary file with pickle.dump() and reload it with pickle.load(), showing the round trip and type preservation.
import pickle
data = {"name": "Alice", "scores": [87, 92, 95], "active": True}
print("Original dict:", data)
with open("safe_demo.pkl", "wb") as f:
pickle.dump(data, f)
with open("safe_demo.pkl", "rb") as f:
loaded = pickle.load(f)
print("Loaded dict:", loaded)
print("Type:", type(loaded).__name__)
print(…
How to Serialize a Dictionary to a Query String in Python
Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.
import urllib.parse
def dict_to_query_string(params):
"""Serialize a dictionary to a URL query string."""
return urllib.parse.urlencode(params)
if __name__ == "__main__":
data = {
"name": "Alice Johnson",
"age": 30,
"city": "New York",
"interests": ["coding", "hiking"]
…
Serialize Python dict to JSON with custom default for datetime
Convert a Python dict containing datetime and set objects into JSON by providing a custom default serializer.
import json
from datetime import datetime
def custom_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, set):
return list(obj)
return str(obj)
data = {
"name": "Alice",
"created_at": datetime(2024, 3, 15, 10, 30, 45),
"tags": {"python", "j…
How to Use __getstate__ and __setstate__ for Pickle in Python
Customize Python object serialization with the pickle __getstate__ and __setstate__ hooks to control exactly what data is stored and how it is restored.
import pickle
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __getstate__(self):
"""Customize what gets pickled."""
state = self.__dict__.copy()
# Convert to Fahrenheit for storage (simulate transformation)
state['fahrenheit'] = (self.celsiu…
How to Convert Data to JSON and Back in Python
Convert a Python dict into a JSON string with indentation, then parse it back into a dict, demonstrating a common round-trip conversion for beginners.
import json
from datetime import datetime
def convert_data(data):
"""Convert a dict into a JSON string and back to dict."""
json_str = json.dumps(data, indent=2)
parsed = json.loads(json_str)
return json_str, parsed
def main():
sample_data = {
"user": "alice",
"message": "hello",
…
How to Serialize Chat Messages to a JSON File in Python
Writes a list of chat message dicts to a JSON file with metadata like export time and message count.
import json
from pathlib import Path
from datetime import datetime
def serialize_messages(messages, output_path):
data = {
"exported_at": datetime.now().isoformat(),
"count": len(messages),
"messages": messages
}
Path(output_path).write_text(
json.dumps(data, indent=2, ensu…
Serialize and Format Data for LLM Prompts in Python
Use dataclasses and the json module to convert Python objects to JSON strings, parse them back, and format structured data into prompt-friendly text for LLM calls.
import json
from dataclasses import dataclass, asdict
@dataclass
class Recipe:
"""Simple data model to represent a recipe."""
name: str
cuisine: str
prep_minutes: int
def to_json(recipe: Recipe) -> str:
"""Serialize a Recipe to a JSON string."""
return json.dumps(asdict(recipe), indent=2)
…
How to Register a Dataset Schema as JSON in Python
Define a catalog of dataset schemas and serialize them to JSON with the standard library json module.
import json
catalog = {
"name": "sample_catalog",
"version": "1.0",
"datasets": [
{
"id": "users",
"type": "table",
"fields": [
{"name": "id", "type": "integer", "key": True},
{"name": "email", "type": "string", "nullable": False}…
How to Convert Python Dict to JSON and Back
Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.
import json
from datetime import datetime, timezone
def convert_data(data, source_format=None, target_format="json"):
"""
Convert Python data structures to txt/json and back.
For beginners: shows how to serialize/deserialize.
"""
if source_format == "json" and target_format == "dict":
ret…
How to Export a Conda Environment YAML File in Python
Generate a mock conda environment YAML export with a reusable Python function and the PyYAML library.
import yaml
def conda_env_mock(name="demo_env", channels=None, packages=None):
channels = channels or ["defaults"]
packages = packages or [
"python=3.11",
"pip",
"numpy=1.24.3",
"pandas=2.0.3",
]
env_dict = {
"name": name,
"channels": channels,
…
Convert Protobuf to JSON and Dict in Python
Provides static helper methods to convert between protobuf messages, JSON strings, and Python dictionaries using the google.protobuf library.
from google.protobuf.json_format import MessageToJson, Parse
import json
class DataConverter:
"""Helper class to convert between protobuf messages and common formats."""
@staticmethod
def to_json(message, indent=2):
"""Convert a protobuf message to JSON string."""
return MessageToJson(me…
Create a Data Helper in Python for gRPC-style APIs
This code builds a simple DataHelper class that mimics gRPC request/response handling with in-memory storage, JSON serialization, and basic CRUD operations for beginners.
import json
from dataclasses import dataclass, asdict
from typing import Dict, Any
@dataclass
class User:
user_id: int
name: str
email: str
class DataHelper:
"""Simple helper to demonstrate gRPC-like data handling for beginners."""
def __init__(self) -> None:
self._users: Dict[int, Use…
Format data in Python using dataclasses like gRPC messages
Convert Python dataclasses to and from dicts and format them gRPC-style for clean data handling.
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
@dataclass
class ProductInfo:
"""Data class representing a gRPC-style product message."""
name: str
price: float
tags: List[str]
description: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
"""C…
How to Serialize a Dataclass to JSON in Python
Serialize a Python dataclass instance to JSON using asdict and json.dumps for API responses or mocks.
from dataclasses import dataclass, asdict
import json
@dataclass
class UserResponse:
id: int
name: str
email: str
active: bool = True
if __name__ == "__main__":
response = UserResponse(id=42, name="Ada Lovelace", email="ada@example.com")
print(json.dumps(asdict(response), indent=2))
Dead Letter Queue Failed Messages List Mock in Python
Implements a simple in-memory dead letter queue to collect, list, and retry failed messages, with JSON serialization for inspection in streaming pipelines.
import json
from collections import deque
class Message:
def __init__(self, message_id, payload, attempts=0):
self.message_id = message_id
self.payload = payload
self.attempts = attempts
def __repr__(self):
return f"Message(id={self.message_id}, attempts={self.attempts})"
c…
How to Encode and Decode Avro Data in Python (Roundtrip)
Serialize a Python dict to Avro binary bytes and decode it back using the fastavro-compatible avro library.
import io
import json
from avro.schema import parse
from avro.io import DatumWriter, DatumReader, BinaryEncoder, BinaryDecoder
def avro_roundtrip(schema_json, data):
schema = parse(json.dumps(schema_json))
bytes_writer = io.BytesIO()
encoder = BinaryEncoder(bytes_writer)
writer = DatumWriter(schema)
…
How to Serialize and Deserialize JSON Event Payloads in Python
Define an EventPayload class with custom to_json and from_json methods to convert event objects to JSON strings and back, using datetime parsing.
import json
from datetime import datetime
class EventPayload:
def __init__(self, event_id, event_type, timestamp, data):
self.event_id = event_id
self.event_type = event_type
self.timestamp = timestamp
self.data = data
def to_json(self):
return json.dumps({
…
Mock Protobuf Binary Encoding in Python
Demonstrates a minimal protobuf-like binary encoding and decoding of an event dataclass using varints and length-delimited fields in pure Python.
import struct
from dataclasses import dataclass
@dataclass
class Event:
id: int
user_id: int
action: str
def encode(self) -> bytes:
# Mock protobuf-like binary encoding using varint and length-delimited fields
buf = bytearray()
# field 1: varint id (tag = (1 << 3) | 0 = 8)
…
How to Cache Data in Redis with Python
Build a simple Redis cache wrapper that stores and retrieves JSON data with automatic TTL and serialization.
import redis
import json
import time
class Cache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db)
self.default_ttl = default_ttl
def get(self, key):
value = self.client.get(key)
if value is None:
…
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.