Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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 Make a Shallow Clone of an Object in Python
Demonstrates using copy.copy() to create a shallow clone of a Python object, showing how nested mutable data is shared while top-level attributes are independent.
import copy
class Config:
def __init__(self):
self.settings = {"volume": 50}
self.user = "admin"
def demonstrate_shallow_copy():
original = Config()
shallow = copy.copy(original)
# Mutating nested object is visible in both (shallow copy share it)
shallow.settings["volume"] = 90…
How to Mirror a Bare Git Repository Backup in Python
Run a git clone --bare subprocess to create a timestamped bare-repo backup folder with error handling.
import subprocess
import shlex
from pathlib import Path
from datetime import datetime
def mirror_bare_repo(source_url: str, backup_dir: str) -> str:
"""Mirror a bare git repository to a timestamped backup folder."""
backup_path = Path(backup_dir)
backup_path.mkdir(parents=True, exist_ok=True)
timest…
How to Implement the Prototype Pattern with Deep Copy in Python
Implements the Prototype design pattern using copy.deepcopy to clone complex objects without sharing mutable state.
import copy
from dataclasses import dataclass, field
from typing import List
@dataclass
class Engine:
horsepower: int
@dataclass
class Car:
brand: str
engine: Engine
accessories: List[str] = field(default_factory=list)
def clone_prototype(car: Car) -> Car:
return copy.deepcopy(car)
if __name__ …
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.