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.
Python code
32 linesclass 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
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
- Use `collections.UserDict` to get dict-like methods for free.
- 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
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.