Skip to content

Commit edfe31e

Browse files
DominicOramxrmx
andauthored
Add optional type hinting to arguments (open-telemetry#4455)
* Add optional to arguments that are optional * Add Optional type hint in all places where arguments are optional * Update some to use | syntax rather than Optional * Fix some more type formatting for Optional --------- Co-authored-by: Riccardo Magliocchetti <[email protected]>
1 parent afec2dd commit edfe31e

File tree

12 files changed

+166
-143
lines changed

12 files changed

+166
-143
lines changed

exporter/opentelemetry-exporter-otlp-proto-common/src/opentelemetry/exporter/otlp/proto/common/_internal/metrics_encoder/__init__.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from __future__ import annotations
15+
1416
import logging
1517
from os import environ
1618
from typing import Dict, List
@@ -66,8 +68,9 @@
6668
class OTLPMetricExporterMixin:
6769
def _common_configuration(
6870
self,
69-
preferred_temporality: Dict[type, AggregationTemporality] = None,
70-
preferred_aggregation: Dict[type, Aggregation] = None,
71+
preferred_temporality: dict[type, AggregationTemporality]
72+
| None = None,
73+
preferred_aggregation: dict[type, Aggregation] | None = None,
7174
) -> None:
7275
MetricExporter.__init__(
7376
self,

exporter/opentelemetry-exporter-otlp-proto-grpc/src/opentelemetry/exporter/otlp/proto/grpc/metric_exporter/__init__.py

+15-13
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
1313

14+
from __future__ import annotations
15+
1416
from dataclasses import replace
1517
from logging import getLogger
1618
from os import environ
17-
from typing import Dict, Iterable, List, Optional, Tuple, Union
19+
from typing import Iterable, List, Tuple, Union
1820
from typing import Sequence as TypingSequence
1921

2022
from grpc import ChannelCredentials, Compression
@@ -92,17 +94,17 @@ class OTLPMetricExporter(
9294

9395
def __init__(
9496
self,
95-
endpoint: Optional[str] = None,
96-
insecure: Optional[bool] = None,
97-
credentials: Optional[ChannelCredentials] = None,
98-
headers: Optional[
99-
Union[TypingSequence[Tuple[str, str]], Dict[str, str], str]
100-
] = None,
101-
timeout: Optional[int] = None,
102-
compression: Optional[Compression] = None,
103-
preferred_temporality: Dict[type, AggregationTemporality] = None,
104-
preferred_aggregation: Dict[type, Aggregation] = None,
105-
max_export_batch_size: Optional[int] = None,
97+
endpoint: str | None = None,
98+
insecure: bool | None = None,
99+
credentials: ChannelCredentials | None = None,
100+
headers: Union[TypingSequence[Tuple[str, str]], dict[str, str], str]
101+
| None = None,
102+
timeout: int | None = None,
103+
compression: Compression | None = None,
104+
preferred_temporality: dict[type, AggregationTemporality]
105+
| None = None,
106+
preferred_aggregation: dict[type, Aggregation] | None = None,
107+
max_export_batch_size: int | None = None,
106108
):
107109
if insecure is None:
108110
insecure = environ.get(OTEL_EXPORTER_OTLP_METRICS_INSECURE)
@@ -146,7 +148,7 @@ def __init__(
146148
compression=compression,
147149
)
148150

149-
self._max_export_batch_size: Optional[int] = max_export_batch_size
151+
self._max_export_batch_size: int | None = max_export_batch_size
150152

151153
def _translate_data(
152154
self, data: MetricsData

exporter/opentelemetry-exporter-otlp-proto-http/src/opentelemetry/exporter/otlp/proto/http/metric_exporter/__init__.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
13+
from __future__ import annotations
1314

1415
import gzip
1516
import logging
@@ -23,7 +24,6 @@
2324
Dict,
2425
List,
2526
Mapping,
26-
Optional,
2727
Sequence,
2828
)
2929

@@ -101,16 +101,17 @@ class OTLPMetricExporter(MetricExporter, OTLPMetricExporterMixin):
101101

102102
def __init__(
103103
self,
104-
endpoint: Optional[str] = None,
105-
certificate_file: Optional[str] = None,
106-
client_key_file: Optional[str] = None,
107-
client_certificate_file: Optional[str] = None,
108-
headers: Optional[Dict[str, str]] = None,
109-
timeout: Optional[int] = None,
110-
compression: Optional[Compression] = None,
111-
session: Optional[requests.Session] = None,
112-
preferred_temporality: Dict[type, AggregationTemporality] = None,
113-
preferred_aggregation: Dict[type, Aggregation] = None,
104+
endpoint: str | None = None,
105+
certificate_file: str | None = None,
106+
client_key_file: str | None = None,
107+
client_certificate_file: str | None = None,
108+
headers: dict[str, str] | None = None,
109+
timeout: int | None = None,
110+
compression: Compression | None = None,
111+
session: requests.Session | None = None,
112+
preferred_temporality: dict[type, AggregationTemporality]
113+
| None = None,
114+
preferred_aggregation: dict[type, Aggregation] | None = None,
114115
):
115116
self._endpoint = endpoint or environ.get(
116117
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT,

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

+27-25
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@
1717
OpenTelemetry SDK Configurator for Easy Instrumentation with Distros
1818
"""
1919

20+
from __future__ import annotations
21+
2022
import logging
2123
import os
2224
from abc import ABC, abstractmethod
2325
from os import environ
24-
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Type, Union
26+
from typing import Callable, Sequence, Type, Union
2527

2628
from typing_extensions import Literal
2729

@@ -91,8 +93,8 @@
9193

9294

9395
def _import_config_components(
94-
selected_components: List[str], entry_point_name: str
95-
) -> Sequence[Tuple[str, object]]:
96+
selected_components: list[str], entry_point_name: str
97+
) -> Sequence[tuple[str, object]]:
9698
component_implementations = []
9799

98100
for selected_component in selected_components:
@@ -123,7 +125,7 @@ def _import_config_components(
123125
return component_implementations
124126

125127

126-
def _get_sampler() -> Optional[str]:
128+
def _get_sampler() -> str | None:
127129
return environ.get(OTEL_TRACES_SAMPLER, None)
128130

129131

@@ -190,10 +192,10 @@ def _get_exporter_names(
190192

191193

192194
def _init_tracing(
193-
exporters: Dict[str, Type[SpanExporter]],
194-
id_generator: IdGenerator = None,
195-
sampler: Sampler = None,
196-
resource: Resource = None,
195+
exporters: dict[str, Type[SpanExporter]],
196+
id_generator: IdGenerator | None = None,
197+
sampler: Sampler | None = None,
198+
resource: Resource | None = None,
197199
):
198200
provider = TracerProvider(
199201
id_generator=id_generator,
@@ -210,10 +212,10 @@ def _init_tracing(
210212

211213

212214
def _init_metrics(
213-
exporters_or_readers: Dict[
215+
exporters_or_readers: dict[
214216
str, Union[Type[MetricExporter], Type[MetricReader]]
215217
],
216-
resource: Resource = None,
218+
resource: Resource | None = None,
217219
):
218220
metric_readers = []
219221

@@ -234,8 +236,8 @@ def _init_metrics(
234236

235237

236238
def _init_logging(
237-
exporters: Dict[str, Type[LogExporter]],
238-
resource: Resource = None,
239+
exporters: dict[str, Type[LogExporter]],
240+
resource: Resource | None = None,
239241
setup_logging_handler: bool = True,
240242
):
241243
provider = LoggerProvider(resource=resource)
@@ -261,10 +263,10 @@ def _import_exporters(
261263
trace_exporter_names: Sequence[str],
262264
metric_exporter_names: Sequence[str],
263265
log_exporter_names: Sequence[str],
264-
) -> Tuple[
265-
Dict[str, Type[SpanExporter]],
266-
Dict[str, Union[Type[MetricExporter], Type[MetricReader]]],
267-
Dict[str, Type[LogExporter]],
266+
) -> tuple[
267+
dict[str, Type[SpanExporter]],
268+
dict[str, Union[Type[MetricExporter], Type[MetricReader]]],
269+
dict[str, Type[LogExporter]],
268270
]:
269271
trace_exporters = {}
270272
metric_exporters = {}
@@ -315,7 +317,7 @@ def _import_sampler_factory(sampler_name: str) -> Callable[[str], Sampler]:
315317
return sampler_impl
316318

317319

318-
def _import_sampler(sampler_name: str) -> Optional[Sampler]:
320+
def _import_sampler(sampler_name: str) -> Sampler | None:
319321
if not sampler_name:
320322
return None
321323
try:
@@ -360,14 +362,14 @@ def _import_id_generator(id_generator_name: str) -> IdGenerator:
360362

361363

362364
def _initialize_components(
363-
auto_instrumentation_version: Optional[str] = None,
364-
trace_exporter_names: Optional[List[str]] = None,
365-
metric_exporter_names: Optional[List[str]] = None,
366-
log_exporter_names: Optional[List[str]] = None,
367-
sampler: Optional[Sampler] = None,
368-
resource_attributes: Optional[Attributes] = None,
369-
id_generator: IdGenerator = None,
370-
setup_logging_handler: Optional[bool] = None,
365+
auto_instrumentation_version: str | None = None,
366+
trace_exporter_names: list[str] | None = None,
367+
metric_exporter_names: list[str] | None = None,
368+
log_exporter_names: list[str] | None = None,
369+
sampler: Sampler | None = None,
370+
resource_attributes: Attributes | None = None,
371+
id_generator: IdGenerator | None = None,
372+
setup_logging_handler: bool | None = None,
371373
):
372374
if trace_exporter_names is None:
373375
trace_exporter_names = []

opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/__init__.py

+30-30
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from __future__ import annotations
1415

1516
import abc
1617
import atexit
@@ -23,7 +24,7 @@
2324
from os import environ
2425
from threading import Lock
2526
from time import time_ns
26-
from typing import Any, Callable, Optional, Tuple, Union # noqa
27+
from typing import Any, Callable, Tuple, Union # noqa
2728

2829
from opentelemetry._logs import Logger as APILogger
2930
from opentelemetry._logs import LoggerProvider as APILoggerProvider
@@ -105,8 +106,8 @@ class LogLimits:
105106

106107
def __init__(
107108
self,
108-
max_attributes: Optional[int] = None,
109-
max_attribute_length: Optional[int] = None,
109+
max_attributes: int | None = None,
110+
max_attribute_length: int | None = None,
110111
):
111112
# attribute count
112113
global_max_attributes = self._from_env_if_absent(
@@ -129,8 +130,8 @@ def __repr__(self):
129130

130131
@classmethod
131132
def _from_env_if_absent(
132-
cls, value: Optional[int], env_var: str, default: Optional[int] = None
133-
) -> Optional[int]:
133+
cls, value: int | None, env_var: str, default: int | None = None
134+
) -> int | None:
134135
if value == cls.UNSET:
135136
return None
136137

@@ -172,17 +173,17 @@ class LogRecord(APILogRecord):
172173

173174
def __init__(
174175
self,
175-
timestamp: Optional[int] = None,
176-
observed_timestamp: Optional[int] = None,
177-
trace_id: Optional[int] = None,
178-
span_id: Optional[int] = None,
179-
trace_flags: Optional[TraceFlags] = None,
180-
severity_text: Optional[str] = None,
181-
severity_number: Optional[SeverityNumber] = None,
182-
body: Optional[AnyValue] = None,
183-
resource: Optional[Resource] = None,
184-
attributes: Optional[Attributes] = None,
185-
limits: Optional[LogLimits] = _UnsetLogLimits,
176+
timestamp: int | None = None,
177+
observed_timestamp: int | None = None,
178+
trace_id: int | None = None,
179+
span_id: int | None = None,
180+
trace_flags: TraceFlags | None = None,
181+
severity_text: str | None = None,
182+
severity_number: SeverityNumber | None = None,
183+
body: AnyValue | None = None,
184+
resource: Resource | None = None,
185+
attributes: Attributes | None = None,
186+
limits: LogLimits | None = _UnsetLogLimits,
186187
):
187188
super().__init__(
188189
**{
@@ -217,7 +218,7 @@ def __eq__(self, other: object) -> bool:
217218
return NotImplemented
218219
return self.__dict__ == other.__dict__
219220

220-
def to_json(self, indent: Optional[int] = 4) -> str:
221+
def to_json(self, indent: int | None = 4) -> str:
221222
return json.dumps(
222223
{
223224
"body": self.body,
@@ -602,12 +603,11 @@ def emit(self, record: LogRecord):
602603
class LoggerProvider(APILoggerProvider):
603604
def __init__(
604605
self,
605-
resource: Resource = None,
606+
resource: Resource | None = None,
606607
shutdown_on_exit: bool = True,
607-
multi_log_record_processor: Union[
608-
SynchronousMultiLogRecordProcessor,
609-
ConcurrentMultiLogRecordProcessor,
610-
] = None,
608+
multi_log_record_processor: SynchronousMultiLogRecordProcessor
609+
| ConcurrentMultiLogRecordProcessor
610+
| None = None,
611611
):
612612
if resource is None:
613613
self._resource = Resource.create({})
@@ -631,9 +631,9 @@ def resource(self):
631631
def _get_logger_no_cache(
632632
self,
633633
name: str,
634-
version: Optional[str] = None,
635-
schema_url: Optional[str] = None,
636-
attributes: Optional[Attributes] = None,
634+
version: str | None = None,
635+
schema_url: str | None = None,
636+
attributes: Attributes | None = None,
637637
) -> Logger:
638638
return Logger(
639639
self._resource,
@@ -649,8 +649,8 @@ def _get_logger_no_cache(
649649
def _get_logger_cached(
650650
self,
651651
name: str,
652-
version: Optional[str] = None,
653-
schema_url: Optional[str] = None,
652+
version: str | None = None,
653+
schema_url: str | None = None,
654654
) -> Logger:
655655
with self._logger_cache_lock:
656656
key = (name, version, schema_url)
@@ -665,9 +665,9 @@ def _get_logger_cached(
665665
def get_logger(
666666
self,
667667
name: str,
668-
version: Optional[str] = None,
669-
schema_url: Optional[str] = None,
670-
attributes: Optional[Attributes] = None,
668+
version: str | None = None,
669+
schema_url: str | None = None,
670+
attributes: Attributes | None = None,
671671
) -> Logger:
672672
if self._disabled:
673673
return NoOpLogger(

opentelemetry-sdk/src/opentelemetry/sdk/_logs/_internal/export/__init__.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
from __future__ import annotations
1415

1516
import abc
1617
import collections
@@ -165,16 +166,16 @@ class BatchLogRecordProcessor(LogRecordProcessor):
165166
"""
166167

167168
_queue: Deque[LogData]
168-
_flush_request: Optional[_FlushRequest]
169-
_log_records: List[Optional[LogData]]
169+
_flush_request: _FlushRequest | None
170+
_log_records: List[LogData | None]
170171

171172
def __init__(
172173
self,
173174
exporter: LogExporter,
174-
schedule_delay_millis: float = None,
175-
max_export_batch_size: int = None,
176-
export_timeout_millis: float = None,
177-
max_queue_size: int = None,
175+
schedule_delay_millis: float | None = None,
176+
max_export_batch_size: int | None = None,
177+
export_timeout_millis: float | None = None,
178+
max_queue_size: int | None = None,
178179
):
179180
if max_queue_size is None:
180181
max_queue_size = BatchLogRecordProcessor._default_max_queue_size()

0 commit comments

Comments
 (0)