@@ -114,11 +114,10 @@ def start_as_current_span(
114114 kind : SpanKind = _SpanKind .INTERNAL ,
115115 attributes : Optional [Attributes ] = None ,
116116 links : Optional [Sequence [Link ]] = None ,
117+ end_on_exit : bool = True ,
117118 ) -> Iterator [Span ]:
118119 """Context manager that starts a span and sets it as the current span in the context.
119120
120- Exiting the context manager will call the span's end method.
121-
122121 .. code:: python
123122
124123 with tracer.start_as_current_span("span_name") as span:
@@ -133,13 +132,34 @@ def start_as_current_span(
133132 :paramtype attributes: Optional[Attributes]
134133 :keyword links: Links to add to the span.
135134 :paramtype links: Optional[Sequence[Link]]
135+ :keyword end_on_exit: Whether to end the span when exiting the context manager. Defaults to True.
136+ :paramtype end_on_exit: bool
136137 :return: The span that was started
137- :rtype: ~opentelemetry.trace.Span
138+ :rtype: Iterator[ ~opentelemetry.trace.Span]
138139 """
139140 span = self .start_span (name , kind = kind , attributes = attributes , links = links )
140- with trace .use_span (span , record_exception = False , end_on_exit = True ) as span : # type: ignore[attr-defined] # pylint: disable=not-context-manager
141+ with trace .use_span ( # pylint: disable=not-context-manager
142+ span , record_exception = False , end_on_exit = end_on_exit
143+ ) as span :
141144 yield span
142145
146+ @classmethod
147+ @contextmanager
148+ def use_span (cls , span : Span , * , end_on_exit : bool = True ) -> Iterator [Span ]:
149+ """Context manager that takes a non-active span and activates it in the current context.
150+
151+ :param span: The span to set as the current span
152+ :type span: ~opentelemetry.trace.Span
153+ :keyword end_on_exit: Whether to end the span when exiting the context manager. Defaults to True.
154+ :paramtype end_on_exit: bool
155+ :return: The span that was activated.
156+ :rtype: Iterator[~opentelemetry.trace.Span]
157+ """
158+ with trace .use_span ( # pylint: disable=not-context-manager
159+ span , record_exception = False , end_on_exit = end_on_exit
160+ ) as active_span :
161+ yield active_span
162+
143163 def _parse_links (self , links : Optional [Sequence [Link ]]) -> Optional [Sequence [OpenTelemetryLink ]]:
144164 if not links :
145165 return None
@@ -189,7 +209,7 @@ def call_with_current_context(*args, **kwargs):
189209
190210 @classmethod
191211 def get_trace_context (cls ) -> Dict [str , str ]:
192- """Returns the Trace Context header values associated with the span.
212+ """Returns the Trace Context header values associated with the current span.
193213
194214 These are generally the W3C Trace Context headers (i.e. "traceparent" and "tracestate").
195215
0 commit comments