diff --git a/CHANGELOG.md b/CHANGELOG.md index a40949fb32e..c137c5c4e0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ([#4458](https://github.com/open-telemetry/opentelemetry-python/pull/4458)) - pylint-ci updated python version to 3.13 ([#4450](https://github.com/open-telemetry/opentelemetry-python/pull/4450)) +- Improve performance of baggage operations + ([#4466](https://github.com/open-telemetry/opentelemetry-python/pull/4466)) ## Version 1.30.0/0.51b0 (2025-02-03) diff --git a/opentelemetry-api/src/opentelemetry/baggage/__init__.py b/opentelemetry-api/src/opentelemetry/baggage/__init__.py index 9a740200a6f..c8e34c1c45b 100644 --- a/opentelemetry-api/src/opentelemetry/baggage/__init__.py +++ b/opentelemetry-api/src/opentelemetry/baggage/__init__.py @@ -15,7 +15,7 @@ from logging import getLogger from re import compile from types import MappingProxyType -from typing import Mapping, Optional +from typing import Dict, Mapping, Optional from opentelemetry.context import create_key, get_value, set_value from opentelemetry.context.context import Context @@ -44,10 +44,7 @@ def get_all( Returns: The name/value pairs in the Baggage """ - baggage = get_value(_BAGGAGE_KEY, context=context) - if isinstance(baggage, dict): - return MappingProxyType(baggage) - return MappingProxyType({}) + return MappingProxyType(_get_baggage_value(context=context)) def get_baggage( @@ -64,7 +61,7 @@ def get_baggage( The value associated with the given name, or null if the given name is not present. """ - return get_all(context=context).get(name) + return _get_baggage_value(context=context).get(name) def set_baggage( @@ -80,7 +77,7 @@ def set_baggage( Returns: A Context with the value updated """ - baggage = dict(get_all(context=context)) + baggage = _get_baggage_value(context=context).copy() baggage[name] = value return set_value(_BAGGAGE_KEY, baggage, context=context) @@ -95,7 +92,7 @@ def remove_baggage(name: str, context: Optional[Context] = None) -> Context: Returns: A Context with the name/value removed """ - baggage = dict(get_all(context=context)) + baggage = _get_baggage_value(context=context).copy() baggage.pop(name, None) return set_value(_BAGGAGE_KEY, baggage, context=context) @@ -113,6 +110,13 @@ def clear(context: Optional[Context] = None) -> Context: return set_value(_BAGGAGE_KEY, {}, context=context) +def _get_baggage_value(context: Optional[Context] = None) -> Dict[str, object]: + baggage = get_value(_BAGGAGE_KEY, context=context) + if isinstance(baggage, dict): + return baggage + return {} + + def _is_valid_key(name: str) -> bool: return _KEY_PATTERN.fullmatch(str(name)) is not None