Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Convert Natural Language Dates to Datetime in Python
Parse common natural language date phrases like 'tomorrow' or 'in 3 days' into Python datetime objects using regex and timedelta.
from datetime import datetime, timedelta
import re
def parse_natural_date(text: str) -> datetime:
"""Convert common natural language date expressions to datetime objects."""
now = datetime.now()
text = text.lower().strip()
# Handle relative dates
patterns = {
r"today": now,
r"…
How to Dump a Debugging Repr for Unknown Types in Python
Build a fallback repr that shows dataclass fields or object attributes for any value, handy when debugging unknown types.
import dataclasses
from typing import Any
@dataclasses.dataclass
class Sample:
name: str
values: list[int]
def dump_repr(obj: Any) -> str:
"""Return a concise but complete repr for debugging unknown types."""
if dataclasses.is_dataclass(obj):
fields = ", ".join(
f"{field.name}={…
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…
Calculate Working Hours Between Two Dates in Python
Compute total business hours (Mon-Fri, 09:00-17:00) between two datetime objects, excluding weekends and non-working hours.
from datetime import datetime, timedelta
def work_hours_between(start: datetime, end: datetime) -> float:
"""Calculate total working hours between two datetimes (Mon-Fri, 09:00-17:00)."""
def is_workday(d: datetime) -> bool:
return d.weekday() < 5
total_hours = 0.0
current = start
whi…
How to Parse NDJSON Lines into a List in Python
Reads a JSON-lines (NDJSON) file line by line and converts each non-empty line into a Python object, returning a list.
import json
from pathlib import Path
def parse_ndjson(file_path: str) -> list:
data = []
with Path(file_path).open("r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
data.append(json.loads(line))
return data
if __name__ == "__main__"…
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 Validate JSON Types per Key in Python
Load a JSON object and validate the type of each key against an expected schema, reporting missing or mismatched fields.
import json
from typing import Any, Dict, Type
def validate_json_types(data: Dict[str, Any], schema: Dict[str, Type]) -> Dict[str, str]:
"""Validate that each key in data matches the expected type in schema."""
errors = {}
for key, expected_type in schema.items():
if key not in data:
e…
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…
Design a Data Helper Class in Python
Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.
class DataPoint:
def __init__(self, x, y):
self.x = x
self.y = y
self.label = None
def describe(self):
"""Return a human-readable description of the data point."""
base = f"DataPoint(x={self.x}, y={self.y})"
return f"{base}, label='{self.label}'" if self.label e…
How to Build a Data Helper Class in Python with OOP
Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.
class DataHelper:
"""A beginner-friendly OOP helper for handling simple datasets."""
def __init__(self, filename):
self.filename = filename
self.data = self._load_data()
def _load_data(self):
"""Load data from a CSV file into a list of dictionaries."""
import csv
…
How to Build a Fluent Interface with the Builder Pattern in Python
Learn to implement a fluent builder pattern in Python by chaining methods that return self, enabling readable object construction.
class Pizza:
def __init__(self):
self.size = None
self.toppings = []
self.crust = None
def set_size(self, size):
self.size = size
return self
def add_topping(self, topping):
self.toppings.append(topping)
return self
def set_crust(self, crust):
…
How to Build an In-Memory CRUD Repository Class in Python
Define a Python Repository class that stores objects in a dictionary and supports create, read, update, delete, and list operations.
class Repository:
def __init__(self):
self._data = {}
def create(self, key, value):
self._data[key] = value
return key
def read(self, key):
return self._data.get(key)
def update(self, key, value):
if key not in self._data:
raise KeyError(f"Key '{ke…
How to Copy Class Instances in Python: Shallow vs Deep Copy
Use copy.copy and copy.deepcopy to clone class instances, showing how nested objects are shared or duplicated.
import copy
class Config:
def __init__(self):
self.settings = {"theme": "dark", "language": "en"}
if __name__ == "__main__":
original = Config()
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)
shallow_copy.settings["theme"] = "light"
deep_copy.settings["them…
How to Define a Simple Class with __init__ and __repr__ in Python
Defines a Person class with __init__ to store name and age, and __repr__ to give a readable string representation.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
if __name__ == "__main__":
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1)
print(p2)
How to Define a Simple Python Class with __init__ and __repr__
Define a basic Python class with an __init__ method to set instance attributes and a __repr__ method for a readable representation of objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
if __name__ == "__main__":
person = Person("Alice", 30)
print(person)
How to Implement Rich Comparison Ordering in Python Classes
This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.
class Task:
def __init__(self, priority, name):
self.priority = priority
self.name = name
def __lt__(self, other):
if not isinstance(other, Task):
return NotImplemented
return self.priority < other.priority
def __eq__(self, other):
if not isinstance(oth…
How to Implement the Command Pattern with Undo in Python
Python code demonstrating the Command design pattern with undo and redo support using action objects and a history manager.
class Command:
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
class AddTextCommand(Command):
def __init__(self, document, text):
self.document = document
self.text = text
def execute(self):
self.document.append(self.tex…
How to Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
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…
Memento Pattern in Python: Save and Restore Object State
Implement the Memento design pattern to snapshot and restore an object's state, demonstrated with a text editor undo feature.
class TextEditor:
def __init__(self, text="", cursor_pos=0):
self.text = text
self.cursor_pos = cursor_pos
def type_text(self, new_text):
self.text += new_text
self.cursor_pos += len(new_text)
def move_cursor(self, pos):
self.cursor_pos = max(0, min(pos, len(self.t…
Python object equality: id vs value comparison
Demonstrates the difference between default identity comparison and custom equality, with a value-based class implementing __eq__ and __hash__.
import copy
class IdOnly:
def __init__(self, name):
self.name = name
class ValueId:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return isinstance(other, ValueId) and self.name == other.name
def __hash__(self):
return hash(self.name)
def…
Visitor Pattern in Python: Double Dispatch Demo
Demonstrates the Visitor design pattern with double dispatch so operations on Dog and Cat objects are selected at runtime without modifying their classes.
class Animal:
def accept(self, visitor):
visitor.visit(self)
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class SoundVisitor:
def visit(self, animal):
if isinstance(animal, Dog):
return self.visit_do…
How to stream parse JSON arrays in Python
This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.
import json
def json_array_stream(items):
"""Generator that yields JSON-encoded values one at a time."""
yield "["
for i, item in enumerate(items):
if i > 0:
yield ","
yield json.dumps(item)
yield "]"
def parse_json_stream(stream):
"""Consumes a stream of JSON fragme…
How to Parse JSON from LLM Model Output Fence in Python
Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.
import json
import re
def parse_json_from_fence(text):
"""
Extract JSON object from a model output that may be wrapped in
triple-backtick fences with optional language tag.
"""
# Match content inside
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.