Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Execute mypy on opentelemetry-sdk/src #4352

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 15 additions & 17 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#4260](https://github.com/open-telemetry/opentelemetry-python/pull/4260))
- semantic-conventions: Bump to 1.29.0
([#4337](https://github.com/open-telemetry/opentelemetry-python/pull/4337))
- sdk: Execute mypy on opentelemety-sdk/src
([#773](https://github.com/open-telemetry/opentelemetry-python/pull/4352))

## Version 1.28.0/0.49b0 (2024-11-05)

Expand Down Expand Up @@ -124,20 +126,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Improve resource field structure for LogRecords
([#3972](https://github.com/open-telemetry/opentelemetry-python/pull/3972))
- Update Semantic Conventions code generation scripts:
- fix namespace exclusion that resulted in dropping `os` and `net` namespaces.
- fix namespace exclusion that resulted in dropping `os` and `net` namespaces.
- add `Final` decorator to constants to prevent collisions
- enable mypy and fix detected issues
- allow to drop specific attributes in preparation for Semantic Conventions v1.26.0
([#3973](https://github.com/open-telemetry/opentelemetry-python/pull/3966))
([#3973](https://github.com/open-telemetry/opentelemetry-python/pull/3966))
- Update semantic conventions to version 1.26.0.
([#3964](https://github.com/open-telemetry/opentelemetry-python/pull/3964))
- Use semconv exception attributes for record exceptions in spans
([#3979](https://github.com/open-telemetry/opentelemetry-python/pull/3979))
- Fix _encode_events assumes events.attributes.dropped exists
- Fix \_encode_events assumes events.attributes.dropped exists
([#3965](https://github.com/open-telemetry/opentelemetry-python/pull/3965))
- Validate links at span creation
([#3991](https://github.com/open-telemetry/opentelemetry-python/pull/3991))
- Add attributes field in `MeterProvider.get_meter` and `InstrumentationScope`
- Add attributes field in `MeterProvider.get_meter` and `InstrumentationScope`
([#4015](https://github.com/open-telemetry/opentelemetry-python/pull/4015))
- Fix inaccessible `SCHEMA_URL` constants in `opentelemetry-semantic-conventions`
([#4069](https://github.com/open-telemetry/opentelemetry-python/pull/4069))
Expand Down Expand Up @@ -167,10 +169,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `SpanAttributes`, `ResourceAttributes`, and `MetricInstruments` are deprecated.
- Attribute and metric definitions are now grouped by the namespace.
- Stable attributes and metrics are moved to `opentelemetry.semconv.attributes`
and `opentelemetry.semconv.metrics` modules.
and `opentelemetry.semconv.metrics` modules.
- Stable and experimental attributes and metrics are defined under
`opentelemetry.semconv._incubating` import path.
([#3586](https://github.com/open-telemetry/opentelemetry-python/pull/3586))
`opentelemetry.semconv._incubating` import path.
([#3586](https://github.com/open-telemetry/opentelemetry-python/pull/3586))
- Rename test objects to avoid pytest warnings
([#3823] (https://github.com/open-telemetry/opentelemetry-python/pull/3823))
- Add span flags to OTLP spans and links
Expand All @@ -182,11 +184,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fix prometheus metric name and unit conversion
([#3924](https://github.com/open-telemetry/opentelemetry-python/pull/3924))
- this is a breaking change to prometheus metric names so they comply with the
[specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.33.0/specification/compatibility/prometheus_and_openmetrics.md#otlp-metric-points-to-prometheus).
[specification](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.33.0/specification/compatibility/prometheus_and_openmetrics.md#otlp-metric-points-to-prometheus).
- you can temporarily opt-out of the unit normalization by setting the environment variable
`OTEL_PYTHON_EXPERIMENTAL_DISABLE_PROMETHEUS_UNIT_NORMALIZATION=true`
`OTEL_PYTHON_EXPERIMENTAL_DISABLE_PROMETHEUS_UNIT_NORMALIZATION=true`
- common unit abbreviations are converted to Prometheus conventions (`s` -> `seconds`),
following the [collector's implementation](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/c0b51136575aa7ba89326d18edb4549e7e1bbdb9/pkg/translator/prometheus/normalize_name.go#L108)
following the [collector's implementation](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/c0b51136575aa7ba89326d18edb4549e7e1bbdb9/pkg/translator/prometheus/normalize_name.go#L108)
- repeated `_` are replaced with a single `_`
- unit annotations (enclosed in curly braces like `{requests}`) are stripped away
- units with slash are converted e.g. `m/s` -> `meters_per_second`.
Expand Down Expand Up @@ -272,7 +274,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## Version 1.21.0/0.42b0 (2023-11-01)

- Fix `SumAggregation`
([#3390](https://github.com/open-telemetry/opentelemetry-python/pull/3390))
([#3390](https://github.com/open-telemetry/opentelemetry-python/pull/3390))
- Fix handling of empty metric collection cycles
([#3335](https://github.com/open-telemetry/opentelemetry-python/pull/3335))
- Fix error when no LoggerProvider configured for LoggingHandler
Expand All @@ -292,7 +294,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Implement Process Resource detector
([#3472](https://github.com/open-telemetry/opentelemetry-python/pull/3472))


## Version 1.20.0/0.41b0 (2023-09-04)

- Modify Prometheus exporter to translate non-monotonic Sums into Gauges
Expand Down Expand Up @@ -321,7 +322,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Default LogRecord observed_timestamp to current timestamp
[#3377](https://github.com/open-telemetry/opentelemetry-python/pull/3377))


## Version 1.18.0/0.39b0 (2023-05-19)

- Select histogram aggregation with an environment variable
Expand All @@ -341,7 +341,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add benchmark tests for metrics
([#3267](https://github.com/open-telemetry/opentelemetry-python/pull/3267))


## Version 1.17.0/0.38b0 (2023-03-22)

- Implement LowMemory temporality
Expand All @@ -361,7 +360,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Version 1.16.0/0.37b0 (2023-02-17)

- Change ``__all__`` to be statically defined.
- Change `__all__` to be statically defined.
([#3143](https://github.com/open-telemetry/opentelemetry-python/pull/3143))
- Remove the ability to set a global metric prefix for Prometheus exporter
([#3137](https://github.com/open-telemetry/opentelemetry-python/pull/3137))
Expand Down Expand Up @@ -401,7 +400,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#3027](https://github.com/open-telemetry/opentelemetry-python/pull/3027))
- Update logging to include logging api as per specification
([#3038](https://github.com/open-telemetry/opentelemetry-python/pull/3038))
- Fix: Avoid generator in metrics _ViewInstrumentMatch.collect()
- Fix: Avoid generator in metrics \_ViewInstrumentMatch.collect()
([#3035](https://github.com/open-telemetry/opentelemetry-python/pull/3035)
- [exporter-otlp-proto-grpc] add user agent string
([#3009](https://github.com/open-telemetry/opentelemetry-python/pull/3009))
Expand Down Expand Up @@ -1689,7 +1688,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Remove dependency on 'backoff' library
([#3679](https://github.com/open-telemetry/opentelemetry-python/pull/3679))


- Make create_gauge non-abstract method
([#3817](https://github.com/open-telemetry/opentelemetry-python/pull/3817))
- Make `tracer.start_as_current_span()` decorator work with async functions
Expand Down
27 changes: 14 additions & 13 deletions opentelemetry-sdk/src/opentelemetry/sdk/error_handler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def _handle(self, error: Exception, *args, **kwargs):

from abc import ABC, abstractmethod
from logging import getLogger
from typing import Optional

from opentelemetry.util._importlib_metadata import entry_points

Expand All @@ -69,7 +70,7 @@ def _handle(self, error: Exception, *args, **kwargs):

class ErrorHandler(ABC):
@abstractmethod
def _handle(self, error: Exception, *args, **kwargs):
def _handle(self, error: Exception, *args, **kwargs) -> None: # type: ignore
"""
Handle an exception
"""
Expand All @@ -83,7 +84,7 @@ class _DefaultErrorHandler(ErrorHandler):
"""

# pylint: disable=useless-return
def _handle(self, error: Exception, *args, **kwargs):
def _handle(self, error: Exception, *args, **kwargs) -> None: # type: ignore
logger.exception("Error handled by default error handler: ")
return None

Expand All @@ -105,26 +106,26 @@ def __new__(cls) -> "GlobalErrorHandler":

return cls._instance

def __enter__(self):
def __enter__(self) -> None:
pass

# pylint: disable=no-self-use
def __exit__(self, exc_type, exc_value, traceback):
if exc_value is None:
def __exit__(self, exc_type, exc_value, traceback) -> Optional[bool]: # type: ignore
if exc_value is None: # type: ignore
return None

plugin_handled = False

error_handler_entry_points = entry_points(
error_handler_entry_points = entry_points( # type: ignore
group="opentelemetry_error_handler"
)

for error_handler_entry_point in error_handler_entry_points:
error_handler_class = error_handler_entry_point.load()
for error_handler_entry_point in error_handler_entry_points: # type: ignore
error_handler_class = error_handler_entry_point.load() # type: ignore

if issubclass(error_handler_class, exc_value.__class__):
if issubclass(error_handler_class, exc_value.__class__): # type: ignore
try:
error_handler_class()._handle(exc_value)
error_handler_class()._handle(exc_value) # type: ignore
plugin_handled = True

# pylint: disable=broad-exception-caught
Expand All @@ -133,11 +134,11 @@ def __exit__(self, exc_type, exc_value, traceback):
"%s error while handling error"
" %s by error handler %s",
error_handling_error.__class__.__name__,
exc_value.__class__.__name__,
error_handler_class.__name__,
exc_value.__class__.__name__, # type: ignore
error_handler_class.__name__, # type: ignore
)

if not plugin_handled:
_DefaultErrorHandler()._handle(exc_value)
_DefaultErrorHandler()._handle(exc_value) # type: ignore

return True
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def collect(self, point_attributes: Attributes) -> Optional[Exemplar]:
{
k: v
for k, v in self.__attributes.items()
if k not in point_attributes
if k not in point_attributes # type: ignore
}
if self.__attributes
else None
Expand Down Expand Up @@ -162,8 +162,8 @@ class BucketIndexError(ValueError):
class FixedSizeExemplarReservoirABC(ExemplarReservoir):
"""Abstract class for a reservoir with fixed size."""

def __init__(self, size: int, **kwargs) -> None:
super().__init__(**kwargs)
def __init__(self, size: int, **kwargs) -> None: # type: ignore
super().__init__(**kwargs) # type: ignore
self._size: int = size
self._reservoir_storage: Mapping[int, ExemplarBucket] = defaultdict(
ExemplarBucket
Expand All @@ -184,7 +184,7 @@ def collect(self, point_attributes: Attributes) -> List[Exemplar]:
exemplars = [
e
for e in (
bucket.collect(point_attributes)
bucket.collect(point_attributes) # type: ignore
for _, bucket in sorted(self._reservoir_storage.items())
)
if e is not None
Expand Down Expand Up @@ -257,8 +257,8 @@ class SimpleFixedSizeExemplarReservoir(FixedSizeExemplarReservoirABC):
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#simplefixedsizeexemplarreservoir
"""

def __init__(self, size: int = 1, **kwargs) -> None:
super().__init__(size, **kwargs)
def __init__(self, size: int = 1, **kwargs) -> None: # type: ignore
super().__init__(size, **kwargs) # type: ignore
self._measurements_seen: int = 0

def _reset(self) -> None:
Expand Down Expand Up @@ -292,8 +292,8 @@ class AlignedHistogramBucketExemplarReservoir(FixedSizeExemplarReservoirABC):
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#alignedhistogrambucketexemplarreservoir
"""

def __init__(self, boundaries: Sequence[float], **kwargs) -> None:
super().__init__(len(boundaries) + 1, **kwargs)
def __init__(self, boundaries: Sequence[float], **kwargs) -> None: # type: ignore
super().__init__(len(boundaries) + 1, **kwargs) # type: ignore
self._boundaries: Sequence[float] = boundaries

def offer(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@
# limitations under the License.

from math import ceil, log2
from typing import List


class Buckets:
# No method of this class is protected by locks because instances of this
# class are only used in methods that are protected by locks themselves.

def __init__(self):
def __init__(self): # type: ignore
self._counts = [0]

# The term index refers to the number of the exponential histogram bucket
Expand Down Expand Up @@ -69,16 +70,16 @@ def index_base(self, value: int) -> None:
self.__index_base = value

@property
def counts(self):
def counts(self) -> List[int]:
return self._counts

def get_offset_counts(self):
def get_offset_counts(self) -> List[int]:
bias = self.__index_base - self.__index_start
return self._counts[-bias:] + self._counts[:-bias]

def grow(self, needed: int, max_size: int) -> None:
size = len(self._counts)
bias = self.__index_base - self.__index_start
size: int = len(self._counts)
bias: int = self.__index_base - self.__index_start
old_positive_limit = size - bias

# 2 ** ceil(log2(needed)) finds the smallest power of two that is larger
Expand All @@ -91,9 +92,9 @@ def grow(self, needed: int, max_size: int) -> None:
# 2 ** ceil(log2(6)) == 8
# 2 ** ceil(log2(7)) == 8
# 2 ** ceil(log2(8)) == 8
new_size = min(2 ** ceil(log2(needed)), max_size)
new_size: int = min(2 ** ceil(log2(needed)), max_size) # type: ignore

new_positive_limit = new_size - bias
new_positive_limit: int = new_size - bias

tmp = [0] * new_size
tmp[new_positive_limit:] = self._counts[old_positive_limit:]
Expand Down Expand Up @@ -176,15 +177,15 @@ def increment_bucket(self, bucket_index: int, increment: int = 1) -> None:
self._counts[bucket_index] += increment

def copy_empty(self) -> "Buckets":
copy = Buckets()
copy = Buckets() # type: ignore

# pylint: disable=no-member
# pylint: disable=protected-access
# pylint: disable=attribute-defined-outside-init
# pylint: disable=invalid-name
copy._Buckets__index_base = self._Buckets__index_base
copy._Buckets__index_start = self._Buckets__index_start
copy._Buckets__index_end = self._Buckets__index_end
copy._Buckets__index_base = self._Buckets__index_base # type: ignore
copy._Buckets__index_start = self._Buckets__index_start # type: ignore
copy._Buckets__index_end = self._Buckets__index_end # type: ignore
copy._counts = [0 for _ in self._counts]

return copy
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,30 @@ class Mapping(ABC):
"""

# pylint: disable=no-member
def __new__(cls, scale: int):
with cls._mappings_lock:
def __new__(cls, scale: int) -> "Mapping":
with cls._mappings_lock: # type: ignore
# cls._mappings and cls._mappings_lock are implemented in each of
# the child classes as a dictionary and a lock, respectively. They
# are not instantiated here because that would lead to both child
# classes having the same instance of cls._mappings and
# cls._mappings_lock.
if scale not in cls._mappings:
cls._mappings[scale] = super().__new__(cls)
cls._mappings[scale]._init(scale)
if scale not in cls._mappings: # type: ignore
cls._mappings[scale] = super().__new__(cls) # type: ignore
cls._mappings[scale]._init(scale) # type: ignore

return cls._mappings[scale]
return cls._mappings[scale] # type: ignore

@abstractmethod
def _init(self, scale: int) -> None:
# pylint: disable=attribute-defined-outside-init

if scale > self._get_max_scale():
# pylint: disable=broad-exception-raised
raise Exception(f"scale is larger than {self._max_scale}")
raise Exception(f"scale is larger than {self._max_scale}") # type: ignore

if scale < self._get_min_scale():
# pylint: disable=broad-exception-raised
raise Exception(f"scale is smaller than {self._min_scale}")
raise Exception(f"scale is smaller than {self._min_scale}") # type: ignore

# The size of the exponential histogram buckets is determined by a
# parameter known as scale, larger values of scale will produce smaller
Expand Down
Loading