Reference library

Python Code Samples

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

7 matches
Cloud + Python medium

Mock Google Pub/Sub publish and pull in Python

A lightweight in-memory mock of Google Pub/Sub with publisher/subscriber classes to test topic-based fan-out and message pulling without real infrastructure.

pubsub gcp testing
Python
import json
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Callable


@dataclass
class Message:
    data: str
    attributes: dict[str, str] = field(default_factory=dict)
    message_id: str | None = None
    ack_id: str | None = None


class MockPublisher:
 …
15 0 Open
Streaming & messaging easy

How to Implement Publish-Subscribe Fanout with Multiple Subscribers in Python

Create a simple publish-subscribe system in Python that broadcasts messages to multiple subscriber callbacks for a given topic.

pubsub messaging events
Python
import time

class PubSub:
    def __init__(self):
        self.subscribers = {}

    def subscribe(self, topic, callback):
        if topic not in self.subscribers:
            self.subscribers[topic] = []
        self.subscribers[topic].append(callback)

    def publish(self, topic, message):
        if topic in sel…
14 0 Open
Streaming & messaging easy

How to Implement an In-Memory Pub/Sub System in Python

This code implements a simple in-memory publish/subscribe system in Python, allowing topics, callbacks, and message broadcasting.

pubsub event-driven design-pattern
Python
class PubSub:
    def __init__(self):
        self.topics = {}

    def subscribe(self, topic, callback):
        if topic not in self.topics:
            self.topics[topic] = []
        self.topics[topic].append(callback)
        return lambda: self.unsubscribe(topic, callback)

    def unsubscribe(self, topic, callb…
18 0 Open
Streaming & messaging medium

How to Mock NATS Subject Hierarchies with Wildcards in Python

Build a lightweight NATS-style pub/sub mock that matches subject hierarchies with '*' and '>' wildcards for tests or prototypes.

nats pubsub wildcards
Python
# Mock a simplified NATS subject hierarchy with wildcard matching
# Supports: exact match, '*' (single token), '>' (tail wildcard)

class NATSSubjectMock:
    def __init__(self):
        self.subscriptions = {}  # subject -> list of callbacks

    def subscribe(self, subject, callback):
        self.subscriptions.setd…
13 0 Open
Streaming & messaging medium

In-Memory PubSub Topic Subscribe Mock in Python

Build a thread-safe in-memory publish/subscribe mock where handlers subscribe to named topics and receive every message published to them.

pubsub mock events
Python
class PubSub:
    def __init__(self):
        self.topics = {}

    def subscribe(self, topic, callback):
        if topic not in self.topics:
            self.topics[topic] = []
        self.topics[topic].append(callback)

    def publish(self, topic, message):
        for callback in self.topics.get(topic, []):
    …
16 0 Open
Streaming & messaging easy

Redis Pub/Sub Channel Subscribe Mock in Python

A lightweight in-memory mock of Redis pub/sub that lets you subscribe to channels, publish messages, and verify handler behavior in tests without a real Redis server.

redis pubsub testing
Python
class MockRedisPubSub:
    def __init__(self):
        self.channels = {}

    def subscribe(self, channel):
        if channel not in self.channels:
            self.channels[channel] = []
        return self.channels[channel]

    def publish(self, channel, message):
        if channel in self.channels:
            …
11 0 Open
Caching & Redis medium

How to Mock Redis Pub/Sub in Python

Test Redis pub/sub logic without a live server using an in-memory fake that queues published messages per channel.

redis pubsub testing
Python
import redis
import time
import threading


class MockRedisPubSub:
    def __init__(self):
        self.channels = {}

    def publish(self, channel, message):
        if channel not in self.channels:
            return 0
        for subscriber in self.channels[channel]:
            subscriber.put(message)
        ret…
13 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.