1515from logging import getLogger
1616from re import compile
1717from types import MappingProxyType
18- from typing import Mapping , Optional
18+ from typing import Dict , Mapping , Optional
1919
2020from opentelemetry .context import create_key , get_value , set_value
2121from opentelemetry .context .context import Context
@@ -44,10 +44,7 @@ def get_all(
4444 Returns:
4545 The name/value pairs in the Baggage
4646 """
47- baggage = get_value (_BAGGAGE_KEY , context = context )
48- if isinstance (baggage , dict ):
49- return MappingProxyType (baggage )
50- return MappingProxyType ({})
47+ return MappingProxyType (_get_baggage_value (context = context ))
5148
5249
5350def get_baggage (
@@ -64,7 +61,7 @@ def get_baggage(
6461 The value associated with the given name, or null if the given name is
6562 not present.
6663 """
67- return get_all (context = context ).get (name )
64+ return _get_baggage_value (context = context ).get (name )
6865
6966
7067def set_baggage (
@@ -80,7 +77,7 @@ def set_baggage(
8077 Returns:
8178 A Context with the value updated
8279 """
83- baggage = dict ( get_all ( context = context ))
80+ baggage = _get_baggage_value ( context = context ). copy ( )
8481 baggage [name ] = value
8582 return set_value (_BAGGAGE_KEY , baggage , context = context )
8683
@@ -95,7 +92,7 @@ def remove_baggage(name: str, context: Optional[Context] = None) -> Context:
9592 Returns:
9693 A Context with the name/value removed
9794 """
98- baggage = dict ( get_all ( context = context ))
95+ baggage = _get_baggage_value ( context = context ). copy ( )
9996 baggage .pop (name , None )
10097
10198 return set_value (_BAGGAGE_KEY , baggage , context = context )
@@ -113,6 +110,13 @@ def clear(context: Optional[Context] = None) -> Context:
113110 return set_value (_BAGGAGE_KEY , {}, context = context )
114111
115112
113+ def _get_baggage_value (context : Optional [Context ] = None ) -> Dict [str , object ]:
114+ baggage = get_value (_BAGGAGE_KEY , context = context )
115+ if isinstance (baggage , dict ):
116+ return baggage
117+ return {}
118+
119+
116120def _is_valid_key (name : str ) -> bool :
117121 return _KEY_PATTERN .fullmatch (str (name )) is not None
118122
0 commit comments