Skip to content

Commit 8a24878

Browse files
committed
Fix some errors found by mypy.
1 parent fff19b5 commit 8a24878

File tree

7 files changed

+53
-48
lines changed

7 files changed

+53
-48
lines changed

opentelemetry-api/src/opentelemetry/context/__init__.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -138,19 +138,14 @@ async def main():
138138
asyncio.run(main())
139139
"""
140140

141-
import typing
142-
143141
from .base_context import BaseRuntimeContext
144142

145143
__all__ = ["Context"]
146144

147-
148-
Context = None # type: typing.Optional[BaseRuntimeContext]
149-
150145
try:
151146
from .async_context import AsyncRuntimeContext
152147

153-
Context = AsyncRuntimeContext()
148+
Context = AsyncRuntimeContext() # type: BaseRuntimeContext
154149
except ImportError:
155150
from .thread_local_context import ThreadLocalRuntimeContext
156151

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ class SpanKind(enum.Enum):
142142
class Span:
143143
"""A span represents a single operation within a trace."""
144144

145-
def start(self, start_time: int = None) -> None:
145+
def start(self, start_time: typing.Optional[int] = None) -> None:
146146
"""Sets the current time as the span's start time.
147147
148148
Each span represents a single operation. The span's start time is the

opentelemetry-sdk/src/opentelemetry/sdk/context/propagation/b3_format.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ class B3Format(HTTPTextFormat):
3535
def extract(cls, get_from_carrier, carrier):
3636
trace_id = format_trace_id(trace.INVALID_TRACE_ID)
3737
span_id = format_span_id(trace.INVALID_SPAN_ID)
38-
sampled = 0
38+
sampled = "0"
3939
flags = None
4040

4141
single_header = _extract_first_element(
@@ -95,8 +95,8 @@ def extract(cls, get_from_carrier, carrier):
9595
# trace an span ids are encoded in hex, so must be converted
9696
trace_id=int(trace_id, 16),
9797
span_id=int(span_id, 16),
98-
trace_options=options,
99-
trace_state={},
98+
trace_options=trace.TraceOptions(options),
99+
trace_state=trace.TraceState(),
100100
)
101101

102102
@classmethod
@@ -111,17 +111,18 @@ def inject(cls, context, set_in_carrier, carrier):
111111
set_in_carrier(carrier, cls.SAMPLED_KEY, "1" if sampled else "0")
112112

113113

114-
def format_trace_id(trace_id: int):
114+
def format_trace_id(trace_id: int) -> str:
115115
"""Format the trace id according to b3 specification."""
116116
return format(trace_id, "032x")
117117

118118

119-
def format_span_id(span_id: int):
119+
def format_span_id(span_id: int) -> str:
120120
"""Format the span id according to b3 specification."""
121121
return format(span_id, "016x")
122122

123123

124-
def _extract_first_element(list_object: list) -> typing.Optional[object]:
125-
if list_object:
126-
return list_object[0]
127-
return None
124+
_T = typing.TypeVar("_T")
125+
126+
127+
def _extract_first_element(items: typing.Iterable[_T]) -> typing.Optional[_T]:
128+
return next(iter(items), None)

opentelemetry-sdk/src/opentelemetry/sdk/metrics/__init__.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ def __init__(
2727
enabled: bool,
2828
monotonic: bool,
2929
):
30-
self.data = 0
30+
self.data = value_type()
3131
self.value_type = value_type
3232
self.enabled = enabled
3333
self.monotonic = monotonic
3434

35-
def _validate_update(self, value: metrics_api.ValueT):
35+
def _validate_update(self, value: metrics_api.ValueT) -> bool:
3636
if not self.enabled:
3737
return False
3838
if not isinstance(value, self.value_type):
@@ -232,7 +232,8 @@ def create_metric(
232232
monotonic: bool = False,
233233
) -> metrics_api.MetricT:
234234
"""See `opentelemetry.metrics.Meter.create_metric`."""
235-
return metric_type(
235+
# Ignore type b/c of mypy bug in addition to missing annotations
236+
return metric_type( # type: ignore
236237
name,
237238
description,
238239
unit,

opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py

+25-22
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,10 @@ class MultiSpanProcessor(SpanProcessor):
7373
def __init__(self):
7474
# use a tuple to avoid race conditions when adding a new span and
7575
# iterating through it on "on_start" and "on_end".
76-
self._span_processors = ()
76+
self._span_processors = () # type: typing.Tuple[SpanProcessor, ...]
7777
self._lock = threading.Lock()
7878

79-
def add_span_processor(self, span_processor: SpanProcessor):
79+
def add_span_processor(self, span_processor: SpanProcessor) -> None:
8080
"""Adds a SpanProcessor to the list handled by this instance."""
8181
with self._lock:
8282
self._span_processors = self._span_processors + (span_processor,)
@@ -122,11 +122,11 @@ class Span(trace_api.Span):
122122
def __init__(
123123
self,
124124
name: str,
125-
context: "trace_api.SpanContext",
125+
context: trace_api.SpanContext,
126126
parent: trace_api.ParentSpan = None,
127-
sampler=None, # TODO
128-
trace_config=None, # TODO
129-
resource=None, # TODO
127+
sampler: None = None, # TODO
128+
trace_config: None = None, # TODO
129+
resource: None = None, # TODO
130130
attributes: types.Attributes = None, # TODO
131131
events: typing.Sequence[trace_api.Event] = None, # TODO
132132
links: typing.Sequence[trace_api.Link] = None, # TODO
@@ -140,9 +140,6 @@ def __init__(
140140
self.sampler = sampler
141141
self.trace_config = trace_config
142142
self.resource = resource
143-
self.attributes = attributes
144-
self.events = events
145-
self.links = links
146143
self.kind = kind
147144

148145
self.span_processor = span_processor
@@ -165,8 +162,8 @@ def __init__(
165162
else:
166163
self.links = BoundedList.from_seq(MAX_NUM_LINKS, links)
167164

168-
self.end_time = None
169-
self.start_time = None
165+
self.end_time = None # type: typing.Optional[int]
166+
self.start_time = None # type: typing.Optional[int]
170167

171168
def __repr__(self):
172169
return '{}(name="{}", context={})'.format(
@@ -203,9 +200,13 @@ def set_attribute(self, key: str, value: types.AttributeValue) -> None:
203200
def add_event(
204201
self, name: str, attributes: types.Attributes = None
205202
) -> None:
206-
if attributes is None:
207-
attributes = Span.empty_attributes
208-
self.add_lazy_event(trace_api.Event(name, util.time_ns(), attributes))
203+
self.add_lazy_event(
204+
trace_api.Event(
205+
name,
206+
util.time_ns(),
207+
Span.empty_attributes if attributes is None else attributes,
208+
)
209+
)
209210

210211
def add_lazy_event(self, event: trace_api.Event) -> None:
211212
with self._lock:
@@ -226,7 +227,9 @@ def add_link(
226227
attributes: types.Attributes = None,
227228
) -> None:
228229
if attributes is None:
229-
attributes = Span.empty_attributes
230+
attributes = (
231+
Span.empty_attributes
232+
) # TODO: empty_attributes is not a Dict. Use Mapping?
230233
self.add_lazy_link(trace_api.Link(link_target_context, attributes))
231234

232235
def add_lazy_link(self, link: "trace_api.Link") -> None:
@@ -242,7 +245,7 @@ def add_lazy_link(self, link: "trace_api.Link") -> None:
242245
return
243246
self.links.append(link)
244247

245-
def start(self, start_time: int = None):
248+
def start(self, start_time: typing.Optional[int] = None) -> None:
246249
with self._lock:
247250
if not self.is_recording_events():
248251
return
@@ -256,7 +259,7 @@ def start(self, start_time: int = None):
256259
return
257260
self.span_processor.on_start(self)
258261

259-
def end(self, end_time: int = None):
262+
def end(self, end_time: int = None) -> None:
260263
with self._lock:
261264
if not self.is_recording_events():
262265
return
@@ -285,7 +288,7 @@ def is_recording_events(self) -> bool:
285288
return True
286289

287290

288-
def generate_span_id():
291+
def generate_span_id() -> int:
289292
"""Get a new random span ID.
290293
291294
Returns:
@@ -294,7 +297,7 @@ def generate_span_id():
294297
return random.getrandbits(64)
295298

296299

297-
def generate_trace_id():
300+
def generate_trace_id() -> int:
298301
"""Get a new random trace ID.
299302
300303
Returns:
@@ -327,7 +330,7 @@ def start_span(
327330
name: str,
328331
parent: trace_api.ParentSpan = trace_api.Tracer.CURRENT_SPAN,
329332
kind: trace_api.SpanKind = trace_api.SpanKind.INTERNAL,
330-
) -> typing.Iterator["Span"]:
333+
) -> typing.Iterator[trace_api.Span]:
331334
"""See `opentelemetry.trace.Tracer.start_span`."""
332335

333336
span = self.create_span(name, parent, kind)
@@ -370,8 +373,8 @@ def create_span(
370373

371374
@contextmanager
372375
def use_span(
373-
self, span: Span, end_on_exit: bool = False
374-
) -> typing.Iterator[Span]:
376+
self, span: trace_api.Span, end_on_exit: bool = False
377+
) -> typing.Iterator[trace_api.Span]:
375378
"""See `opentelemetry.trace.Tracer.use_span`."""
376379
try:
377380
span_snapshot = self._current_span_slot.get()

opentelemetry-sdk/src/opentelemetry/sdk/trace/export/__init__.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@ def __init__(
118118
)
119119

120120
self.span_exporter = span_exporter
121-
self.queue = collections.deque([], max_queue_size)
121+
self.queue = collections.deque(
122+
[], max_queue_size
123+
) # type: typing.Deque[Span]
122124
self.worker_thread = threading.Thread(target=self.worker, daemon=True)
123125
self.condition = threading.Condition(threading.Lock())
124126
self.schedule_delay_millis = schedule_delay_millis
@@ -128,7 +130,9 @@ def __init__(
128130
# flag that indicates that spans are being dropped
129131
self._spans_dropped = False
130132
# precallocated list to send spans to exporter
131-
self.spans_list = [None] * self.max_export_batch_size
133+
self.spans_list = [
134+
None
135+
] * self.max_export_batch_size # type: typing.List[typing.Optional[Span]]
132136
self.worker_thread.start()
133137

134138
def on_start(self, span: Span) -> None:
@@ -172,7 +176,7 @@ def worker(self):
172176
# be sure that all spans are sent
173177
self._flush()
174178

175-
def export(self) -> bool:
179+
def export(self) -> None:
176180
"""Exports at most max_export_batch_size spans."""
177181
idx = 0
178182

@@ -184,7 +188,8 @@ def export(self) -> bool:
184188
suppress_instrumentation = Context.suppress_instrumentation
185189
try:
186190
Context.suppress_instrumentation = True
187-
self.span_exporter.export(self.spans_list[:idx])
191+
# Ignore type b/c the Optional[None]+slicing is too "clever" for mypy
192+
self.span_exporter.export(self.spans_list[:idx]) # type: ignore
188193
# pylint: disable=broad-except
189194
except Exception:
190195
logger.exception("Exception while exporting data.")

opentelemetry-sdk/src/opentelemetry/sdk/util.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ class BoundedList(Sequence):
4646

4747
def __init__(self, maxlen):
4848
self.dropped = 0
49-
self._dq = deque(maxlen=maxlen)
49+
self._dq = deque(maxlen=maxlen) # type: deque
5050
self._lock = threading.Lock()
5151

5252
def __repr__(self):
@@ -98,8 +98,8 @@ def __init__(self, maxlen):
9898
raise ValueError
9999
self.maxlen = maxlen
100100
self.dropped = 0
101-
self._dict = OrderedDict()
102-
self._lock = threading.Lock()
101+
self._dict = OrderedDict() # type: OrderedDict
102+
self._lock = threading.Lock() # type: threading.Lock
103103

104104
def __repr__(self):
105105
return "{}({}, maxlen={})".format(

0 commit comments

Comments
 (0)