Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

8 matches
Files & data easy

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.

file permissions os.walk audit
Python
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…
56 0 Open
Files & data easy

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.

shutil file-copy pathlib
Python
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:…
11 0 Open
Dictionaries & sets easy

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.

sets intersection permissions
Python
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…
12 0 Open
Automation & scripting medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
36 0 Open
Automation & scripting easy

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.

chmod permissions secrets
Python
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}")
    
   …
13 0 Open
API design & gRPC easy

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.

decorator rbac permissions
Python
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):
          …
13 0 Open
API design & gRPC easy

Scope-based authorization in Python

A simple Python class that checks user scopes against required permissions for a resource, returning an authorization decision.

authorization scopes oauth
Python
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…
12 0 Open
Auth & security at scale easy

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.

permissions-policy mock security
Python
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…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.