Reference library

Python Code Samples

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

3 matches
Testing & modern typing easy

How to Share Fixtures Across Tests with pytest conftest

Learn how to define pytest fixtures in conftest.py and control their scope (function, module, session) so every test in a directory reuses the same setup and teardown.

pytest fixtures conftest
Python
import pytest

@pytest.fixture
def sample_data():
    """Simple fixture available to all tests in this directory."""
    return {"name": "Alice", "age": 30}

@pytest.fixture(scope="session")
def session_data():
    """Fixture created once per test session."""
    return {"session_id": 12345}

@pytest.fixture(scope="mo…
13 0 Open
API design & gRPC medium

How to Mock OAuth2 Bearer Token Auth Middleware in Python

Create a simple OAuth2 bearer token authentication middleware that verifies signed tokens and enforces scope-based access control.

oauth2 security middleware
Python
import hmac
import time
import base64
import json
from functools import wraps

VALID_TOKENS = {"test_token_123": {"user": "alice", "scope": "read:posts"}}


def generate_token(username: str) -> str:
    payload = {"user": username, "iat": int(time.time())}
    encoded = base64.urlsafe_b64encode(json.dumps(payload).enc…
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

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.