Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Audit File Permissions Across a Project in Python
Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.
import os
import stat
from pathlib import Path
def audit_file_permissions(project_root):
"""Walk through project_root and print path, owner, and permissions for every file."""
results = []
for root, dirs, files in os.walk(project_root):
for name in files + dirs:
full_path = os.path.joi…
How to Copy a File with shutil.copy2 in Python
Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.
import shutil
from pathlib import Path
source = Path("sample.txt")
destination = Path("sample_copy.txt")
source.write_text("Hello, PythonSkillset!")
if __name__ == "__main__":
shutil.copy2(source, destination)
copied = destination.read_text()
print(f"Copied content: {copied}")
print(f"Source exists:…
How to Find the Intersection of Permission Sets in Python
This code defines a function that takes a list of permission sets and returns a set containing only the permissions common to all sets, with a short-circuit for empty results.
from typing import Set
def intersect_permissions(permission_sets: list[Set[str]]) -> Set[str]:
"""
Given a list of permission sets, return the common permissions
present in every set.
"""
if not permission_sets:
return set()
common = permission_sets[0]
for perm_set in permissi…
Restrict Secrets File Permissions with the chmod Script in Python
This script restricts a secrets file to 0600 permissions, rotates it to a dated backup, and creates a fresh protected file for secure automation workflows.
import os
import sys
import stat
from pathlib import Path
def restrict_secrets_file(filepath: str) -> None:
"""Set restrictive permissions (0600) on a secrets file."""
path = Path(filepath).expanduser()
if not path.is_file():
raise FileNotFoundError(f"Secrets file not found: {path}")
…
How to Implement RBAC Permission Checks with a Route Decorator in Python
Build a reusable Python decorator that checks a user's role against allowed roles and raises a custom PermissionError when access is denied.
from functools import wraps
from enum import Enum
class Role(Enum):
ADMIN = "admin"
MODERATOR = "moderator"
USER = "user"
class PermissionError(Exception):
pass
def require_role(*allowed_roles):
def decorator(func):
@wraps(func)
def wrapper(user_role, *args, **kwargs):
…
Scope-based authorization in Python
A simple Python class that checks user scopes against required permissions for a resource, returning an authorization decision.
class ScopeAuthorization:
def __init__(self):
self.scopes = {
"read": ["resource:read"],
"write": ["resource:read", "resource:write"],
"admin": ["resource:read", "resource:write", "resource:delete"]
}
def authorize(self, user_scopes, required_scope, resource…
How to Mock a Permissions Policy in Python
A lightweight Python class that simulates a browser Permissions-Policy header by tracking allowed/ denied feature permissions with get, set, reset, and bulk operations.
class PermissionsPolicy:
def __init__(self):
self._features = {
"geolocation": "self",
"camera": "self",
"microphone": "self",
"payment": "self",
"usb": "self",
}
def get_feature_policy(self, feature):
return self._features.ge…
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.