How to Mock a Baggage Context (Key-Value Store) in Python

This code implements an in-memory key-value mock of a baggage context, letting you set, get, check, and delete keys for tracing-style metadata.

Easy Python 3.9+ Aug 9, 2026 Observability & SRE 15 views 0 copies

Python code

32 lines
Python 3.9+
class BaggageContext:
    def __init__(self):
        self._store = {}

    def set(self, key, value):
        self._store[key] = value
        return value

    def get(self, key, default=None):
        return self._store.get(key, default)

    def has(self, key):
        return key in self._store

    def delete(self, key):
        return self._store.pop(key, None)

    def keys(self):
        return list(self._store.keys())


if __name__ == "__main__":
    baggage = BaggageContext()
    baggage.set("user_id", 12345)
    baggage.set("session_token", "abc-def-ghi")

    print(baggage.get("user_id"))
    print(baggage.has("session_token"))
    print(baggage.get("unknown_key", "default-value"))
    print(baggage.keys())
    baggage.delete("session_token")
    print(baggage.has("session_token"))

Output

stdout
12345
True
default-value
['user_id', 'session_token']
False

How it works

The class wraps a plain dict to simulate a baggage context, a common pattern in distributed tracing for passing metadata like user IDs and trace IDs. Each method (set/get/has/delete/keys) maps directly to dict operations, so behavior is predictable and lightweight. The mock is useful for unit tests where you want to avoid coupling to an external tracing library. By implementing a minimal interface, you can later swap in a real baggage implementation without changing your test code.

Common mistakes

  • Forgetting that `delete` returns the value or `None`, which may confuse callers expecting a boolean.
  • Not handling thread safety; the mock is not thread-safe, so concurrent access could cause race conditions.
  • Using a mutable default argument for `get` — though here it is safe because the default is `None`.

Variations

  1. Use `collections.UserDict` to get dict-like methods for free.
  2. Add type hints with `TypedDict` or generic `dict[str, Any]` for better IDE support.

Real-world use cases

  • In unit tests, mock the baggage context to verify that your service passes user_id and trace_id correctly through function calls.
  • When integrating with an observability SDK (e.g., OpenTelemetry), use a mock to test logic that reads baggage without sending real telemetry data.
  • In a microservice, use a lightweight in-memory baggage store to propagate request-scoped metadata like authentication tokens across internal service calls.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Observability & SRE

Related tutorials and quizzes for this topic.