Skip to content

Commit f1db112

Browse files
authored
Add __getnewargs__ to SpanContext class (open-telemetry#1380)
1 parent 1d03c34 commit f1db112

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

opentelemetry-api/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
## Unreleased
44

55
- Add optional parameter to `record_exception` method ([#1314](https://github.com/open-telemetry/opentelemetry-python/pull/1314))
6+
- Add pickle support to SpanContext class ([#1380](https://github.com/open-telemetry/opentelemetry-python/pull/1380))
67

78
## Version 0.15b0
89

opentelemetry-api/src/opentelemetry/trace/span.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,17 @@ def __new__(
190190
(trace_id, span_id, is_remote, trace_flags, trace_state, is_valid),
191191
)
192192

193+
def __getnewargs__(
194+
self,
195+
) -> typing.Tuple[int, int, bool, "TraceFlags", "TraceState"]:
196+
return (
197+
self.trace_id,
198+
self.span_id,
199+
self.is_remote,
200+
self.trace_flags,
201+
self.trace_state,
202+
)
203+
193204
@property
194205
def trace_id(self) -> int:
195206
return self[0] # pylint: disable=unsubscriptable-object
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import pickle
16+
import unittest
17+
18+
from opentelemetry import trace
19+
20+
21+
class TestSpanContext(unittest.TestCase):
22+
def test_span_context_pickle(self):
23+
"""
24+
SpanContext needs to be pickleable to support multiprocessing
25+
so span can start as parent from the new spawned process
26+
"""
27+
sc = trace.SpanContext(
28+
1,
29+
2,
30+
is_remote=False,
31+
trace_flags=trace.DEFAULT_TRACE_OPTIONS,
32+
trace_state=trace.DEFAULT_TRACE_STATE,
33+
)
34+
pickle_sc = pickle.loads(pickle.dumps(sc))
35+
self.assertEqual(sc.trace_id, pickle_sc.trace_id)
36+
self.assertEqual(sc.span_id, pickle_sc.span_id)

0 commit comments

Comments
 (0)