Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Serialize an Exception to a JSON-Safe Dict in Python
Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.
import json
import traceback
from typing import Any
def exception_to_dict(exc: Exception) -> dict[str, Any]:
"""Convert an exception into a JSON-safe dictionary."""
return {
"type": type(exc).__name__,
"message": str(exc),
"traceback": traceback.format_exc().strip().split("\n")[-3:],
…
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 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 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 Create a Simple Data Helper in Python for LLM Projects
Create a beginner-friendly Python class that stores, filters, and serializes data records for AI/LLM workflows.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Simple helper for beginners to manage data in AI/LLM projects."""
def __init__(self, data: Optional[List[Dict[str, Any]]] = None) -> None:
self.data: List[Dict[str, Any]] = data or []
def add_item(self, item: Dict[str…
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 Save a VM Snapshot State to a JSON File in Python
Define a dataclass for a VM snapshot and serialize it to a JSON file, then reload it to verify the state.
import json
from dataclasses import dataclass, asdict
from pathlib import Path
@dataclass
class VMSnapshot:
name: str
memory_mb: int
disk_gb: int
state: str = "saved"
def snapshot_to_file(self, path: Path) -> str:
"""Write snapshot state to a JSON file and return the filename."""
…
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 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))
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({
…
How to Serialize Cache Values with JSON and Pickle in Python
Serialize cache values using JSON for simple types or pickle for arbitrary objects, with robust error handling for unsupported types like mocks.
import json
import pickle
from unittest.mock import Mock
def serialize(value, method="json"):
"""Serialize a cache value using JSON or pickle with type checking."""
if method == "json":
try:
return json.dumps(value).encode("utf-8")
except TypeError as e:
raise ValueErro…
How to Implement a Data Helper for Microservices in Python
Create a reusable helper class to serialize, deserialize, and wrap data for microservice communication using dataclasses and JSON.
import json
from dataclasses import dataclass, asdict
from typing import Any, Dict, List
@dataclass
class ServiceResponse:
status: str
data: Any
message: str = ""
class DataHelper:
"""Simple helper for microservice data handling."""
@staticmethod
def serialize(data: Dict[str, Any]) -> str:…
How to Save and Load a Mock Model with Pickle and joblib in Python
Serialize a custom machine learning model to a .joblib file with joblib.dump, reload it, and run a prediction with joblib.load.
import joblib
from pathlib import Path
class MockModel:
def __init__(self, weights):
self.weights = weights
def predict(self, features):
return sum(w * f for w, f in zip(self.weights, features))
def save_model_pickle(model, filepath):
with open(filepath, "wb") as f:
joblib.dump(…
How to Define a Mock Primary Metric in Python
Define a mock primary metric object with a name, value, and unit, and serialize it to a dictionary for experimentation and testing.
class Metric:
def __init__(self, name, value, unit=None):
self.name = name
self.value = value
self.unit = unit
def to_dict(self):
result = {"name": self.name, "value": self.value}
if self.unit:
result["unit"] = self.unit
return result
def __repr…
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.