@@ -376,30 +376,33 @@ def create_span(
376
376
as a child of the current span in this tracer's context, or as a root
377
377
span if no current span exists.
378
378
"""
379
+ span_id = generate_span_id ()
379
380
380
381
if parent is Tracer .CURRENT_SPAN :
381
382
parent = self .get_current_span ()
382
383
383
- if parent is None :
384
- parent_context = None
385
- new_span_context = trace_api .SpanContext (
386
- generate_trace_id (), generate_span_id ()
387
- )
384
+ parent_context = parent
385
+ if isinstance (parent_context , trace_api .Span ):
386
+ parent_context = parent .get_context ()
387
+
388
+ if parent_context is not None and not isinstance (
389
+ parent_context , trace_api .SpanContext
390
+ ):
391
+ raise TypeError
392
+
393
+ if parent_context is None or not parent_context .is_valid ():
394
+ parent = parent_context = None
395
+ trace_id = generate_trace_id ()
396
+ trace_options = None
397
+ trace_state = None
388
398
else :
389
- if isinstance (parent , trace_api .Span ):
390
- parent_context = parent .get_context ()
391
- elif isinstance (parent , trace_api .SpanContext ):
392
- parent_context = parent
393
- else :
394
- # TODO: error handling
395
- raise TypeError
396
-
397
- new_span_context = trace_api .SpanContext (
398
- parent_context .trace_id ,
399
- generate_span_id (),
400
- parent_context .trace_options ,
401
- parent_context .trace_state ,
402
- )
399
+ trace_id = parent_context .trace_id
400
+ trace_options = parent_context .trace_options
401
+ trace_state = parent_context .trace_state
402
+
403
+ context = trace_api .SpanContext (
404
+ trace_id , span_id , trace_options , trace_state
405
+ )
403
406
404
407
# The sampler decides whether to create a real or no-op span at the
405
408
# time of span creation. No-op spans do not record events, and are not
@@ -408,23 +411,24 @@ def create_span(
408
411
# to include information about the sampling decision.
409
412
sampling_decision = self .sampler .should_sample (
410
413
parent_context ,
411
- new_span_context .trace_id ,
412
- new_span_context .span_id ,
414
+ context .trace_id ,
415
+ context .span_id ,
413
416
name ,
414
417
{}, # TODO: links
415
418
)
416
419
417
420
if sampling_decision .sampled :
418
421
return Span (
419
422
name = name ,
420
- context = new_span_context ,
423
+ context = context ,
421
424
parent = parent ,
422
425
sampler = self .sampler ,
423
426
attributes = sampling_decision .attributes ,
424
427
span_processor = self ._active_span_processor ,
425
428
kind = kind ,
426
429
)
427
- return trace_api .DefaultSpan (context = new_span_context )
430
+
431
+ return trace_api .DefaultSpan (context = context )
428
432
429
433
@contextmanager
430
434
def use_span (
0 commit comments