Reference library

Python Code Samples

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

4 matches
Git + Python easy

Create a Mock GitHub Release API in Python for Testing gh CLI

Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.

mock-api github testing
Python
import json
from unittest.mock import patch, Mock

class GitHubReleaseAPI:
    """Mock GitHub Releases API for testing gh CLI stub behavior."""
    
    def __init__(self):
        self.releases = {}
        self.counter = 1
    
    def create_release(self, repo, tag, name=None, notes=None):
        release_id = self…
16 0 Open
Testing & modern typing easy

How to Write a pytest Test Function with assert Equal in Python

Define simple pytest test functions that use assert to verify result equality and run them with pytest.main.

pytest unit testing assert
Python
import pytest

def add(a, b):
    return a + b

def test_add_positive_numbers():
    result = add(2, 3)
    assert result == 5

def test_add_negative_numbers():
    result = add(-2, -3)
    assert result == -5

def test_add_mixed_numbers():
    result = add(2, -3)
    assert result == -1

if __name__ == "__main__":
  …
11 0 Open
Testing & modern typing easy

Interface Segregation with Fake Test Implementations in Python

Defines segregated abstract interfaces (Printer, Scanner) and uses a FakePrinter to record calls for unit testing without real resources.

abc interface-segregation testing
Python
from abc import ABC, abstractmethod


class Printer(ABC):
    @abstractmethod
    def print_document(self, doc: str) -> str:
        pass


class Scanner(ABC):
    @abstractmethod
    def scan_document(self) -> str:
        pass


class MultiFunctionPrinter(Printer, Scanner):
    def print_document(self, doc: str) -> …
13 0 Open
ML engineering pipelines easy

How to Mock train_test_split in Python for Unit Testing

Build a lightweight mock of sklearn's train_test_split to unit test ML pipeline code without needing the full library or deterministic random state.

train_test_split mock unit-testing
Python
import numpy as np
from sklearn.model_selection import train_test_split
from unittest.mock import patch

def mock_train_test_split(X, y, test_size=0.25, random_state=None, **kwargs):
    """A simple mock implementation of train_test_split."""
    n_samples = len(X)
    n_test = int(n_samples * test_size)
    n_train =…
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.