Skip to content
Open
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
1 change: 1 addition & 0 deletions .changelog/5491.changed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`opentelemetry-python`: enable Ruff default ruleset and fix auto-fixable lint issues
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,7 @@ def _get_module_path(self, proto_file: str) -> str:
Python module path (dot-separated)
"""
transformed = self._transform_proto_path(proto_file)
if transformed.endswith(".py"):
transformed = transformed[:-3]
transformed = transformed.removesuffix(".py")
return transformed.replace("/", ".")

def _generate_file(self, file_desc: descriptor.FileDescriptorProto) -> str:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import math
import typing

from typing_extensions import Self

T = typing.TypeVar("T")
M = typing.TypeVar("M", bound="JsonMessage")

Expand Down Expand Up @@ -39,7 +41,7 @@ def to_json(self) -> str:
return json.dumps(self.to_dict())

@classmethod
def from_json(cls: type[M], data: str | bytes) -> M:
def from_json(cls, data: str | bytes) -> Self:
"""
Deserialize from a JSON string or bytes.
"""
Expand Down Expand Up @@ -179,7 +181,7 @@ def decode_int64(value: int | str | None, field_name: str) -> int:
) from None


def decode_float(value: float | int | str | None, field_name: str) -> float:
def decode_float(value: float | str | None, field_name: str) -> float:
"""
Parse float/double from number or string, handling special values.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,7 @@ def test_encode_float(value: float, expected: float | str) -> None:
(None, 0.0),
],
)
def test_decode_float(
value: float | int | str | None, expected: float
) -> None:
def test_decode_float(value: float | str | None, expected: float) -> None:
result = decode_float(value, "field")
if math.isnan(expected):
assert math.isnan(result)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# SPDX-License-Identifier: Apache-2.0

# pylint: skip-file
# ruff: noqa: PLC0415

import base64
from typing import Any
Expand Down
1 change: 0 additions & 1 deletion codegen/opentelemetry-codegen-json/tests/test_serde.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# SPDX-License-Identifier: Apache-2.0

# pylint: skip-file
# ruff: noqa: PLC0415

import json
import math
Expand Down
2 changes: 1 addition & 1 deletion dev-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ asgiref==3.7.2
psutil==7.2.2
GitPython==3.1.52
pre-commit==3.7.0
ruff==0.16.0
ruff==0.16.1
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@
# "AnyValue" forward reference in opentelemetry.util.types._ExtendedAttributes
# resolves when sphinx_autodoc_typehints calls typing.get_type_hints() on
# BoundedAttributes (whose __globals__ is the attributes module). Docs-only.
import opentelemetry.attributes # noqa: E402
from opentelemetry.util.types import AnyValue as _AnyValue # noqa: E402
import opentelemetry.attributes
from opentelemetry.util.types import AnyValue as _AnyValue

opentelemetry.attributes.AnyValue = _AnyValue

Expand Down
2 changes: 1 addition & 1 deletion docs/examples/django/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def main():
DjangoInstrumentor().instrument()

try:
from django.core.management import ( # noqa: PLC0415
from django.core.management import (
execute_from_command_line,
)
except ImportError as exc:
Expand Down
7 changes: 3 additions & 4 deletions docs/examples/opencensus-exporter-tracer/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
span_processor = BatchSpanProcessor(exporter)

trace.get_tracer_provider().add_span_processor(span_processor)
with tracer.start_as_current_span("foo"):
with tracer.start_as_current_span("bar"):
with tracer.start_as_current_span("baz"):
print("Hello world from OpenTelemetry Python!")
with tracer.start_as_current_span("foo"), tracer.start_as_current_span("bar"):
with tracer.start_as_current_span("baz"):
print("Hello world from OpenTelemetry Python!")
7 changes: 3 additions & 4 deletions docs/getting_started/tracing_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("foo"):
with tracer.start_as_current_span("bar"):
with tracer.start_as_current_span("baz"):
print("Hello world from OpenTelemetry Python!")
with tracer.start_as_current_span("foo"), tracer.start_as_current_span("bar"):
with tracer.start_as_current_span("baz"):
print("Hello world from OpenTelemetry Python!")
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def _load_http_transport_factory(name: str) -> BaseHTTPTransportFactory:
if name in _KNOWN_TRANSPORTS:
return _KNOWN_TRANSPORTS[name]
# pylint: disable-next=import-outside-toplevel,import-error
from opentelemetry.util._importlib_metadata import ( # noqa: PLC0415
from opentelemetry.util._importlib_metadata import (
entry_points,
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
@functools.cache
def _get_connection_error_types() -> tuple[type[Exception], ...]:
# pylint: disable-next=import-outside-toplevel
import requests.exceptions # noqa: PLC0415
import requests.exceptions

return (
requests.exceptions.ConnectionError,
Expand Down Expand Up @@ -71,7 +71,7 @@ def __init__(
**kwargs: Any,
) -> None:
# pylint: disable-next=import-outside-toplevel
import requests # noqa: PLC0415
import requests

self._session = session if session is not None else requests.Session()
self._session.verify = verify
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
@functools.cache
def _get_connection_error_types() -> tuple[type[Exception], ...]:
# pylint: disable-next=import-outside-toplevel
import urllib3.exceptions # noqa: PLC0415
import urllib3.exceptions

types: list[type[Exception]] = [
urllib3.exceptions.ConnectionError,
Expand Down Expand Up @@ -75,7 +75,7 @@ def __init__(
**kwargs: Any,
) -> None:
# pylint: disable-next=import-outside-toplevel
import urllib3 # noqa: PLC0415
import urllib3

pool_kwargs: dict[str, object] = {
"retries": urllib3.Retry(0, redirect=False),
Expand Down Expand Up @@ -104,7 +104,7 @@ def request(
data: bytes | None = None,
) -> BaseHTTPResult:
# pylint: disable-next=import-outside-toplevel
import urllib3 # noqa: PLC0415
import urllib3

try:
response = self._pool.request(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,15 +307,13 @@ def test_export(self):
# pylint: disable=unsubscriptable-object
export_arg = mock_export.call_args[0]
service_request = next(export_arg[0])
output_spans = getattr(service_request, "spans")
output_node = getattr(service_request, "node")
output_spans = service_request.spans
output_node = service_request.node
self.assertEqual(len(output_spans), 1)
self.assertIsNotNone(getattr(output_node, "library_info"))
self.assertIsNotNone(getattr(output_node, "service_info"))
output_identifier = getattr(output_node, "identifier")
self.assertEqual(
getattr(output_identifier, "host_name"), "testHostName"
)
self.assertIsNotNone(output_node.library_info)
self.assertIsNotNone(output_node.service_info)
output_identifier = output_node.identifier
self.assertEqual(output_identifier.host_name, "testHostName")

def test_export_service_name(self):
trace_api.set_tracer_provider(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,14 @@ def test_temporality_lowmemory_env(self):
self.assertEqual(result[instrument_class], expected)

def test_temporality_invalid_env_logs_warning(self):
with patch.dict(
"os.environ",
{OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "INVALID"},
with (
patch.dict(
"os.environ",
{OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: "INVALID"},
),
self.assertLogs(_AGGREGATION_LOGGER_NAME, level="WARNING"),
):
with self.assertLogs(_AGGREGATION_LOGGER_NAME, level="WARNING"):
result = _get_temporality(None)
result = _get_temporality(None)
self.assertEqual(
result[Counter],
AggregationTemporality.CUMULATIVE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,6 @@ def _exporting(self) -> str:
Returns a string that describes the overall exporter, to be used in
warning messages.
"""
pass

def _set_meter_provider(self, meter_provider: MeterProvider) -> None:
self._metrics = create_exporter_metrics(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from opentelemetry.exporter.otlp.proto.common.trace_encoder import (
encode_spans,
)
from opentelemetry.exporter.otlp.proto.grpc.exporter import ( # noqa: F401
from opentelemetry.exporter.otlp.proto.grpc.exporter import (
_RETRYABLE_ERROR_CODES,
InvalidCompressionValueException,
OTLPExporterMixin,
Expand Down Expand Up @@ -184,11 +184,9 @@ def setUp(self):
self.span = _Span(
"a",
context=Mock(
**{
"trace_state": {"a": "b", "c": "d"},
"span_id": 10217189687419569865,
"trace_id": 67545097771067222548457157018666467027,
}
trace_state={"a": "b", "c": "d"},
span_id=10217189687419569865,
trace_id=67545097771067222548457157018666467027,
),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,27 +73,21 @@ def setUp(self):
self.tracer = tracer_provider.get_tracer(__name__)

event_mock = Mock(
**{
"timestamp": 1591240820506462784,
"attributes": BoundedAttributes(
attributes={"a": 1, "b": False}
),
}
timestamp=1591240820506462784,
attributes=BoundedAttributes(attributes={"a": 1, "b": False}),
)

type(event_mock).name = PropertyMock(return_value="a")
type(event_mock).dropped_attributes = PropertyMock(return_value=0)
self.span = _Span(
"a",
context=Mock(
**{
"trace_state": {"a": "b", "c": "d"},
"span_id": 10217189687419569865,
"trace_id": 67545097771067222548457157018666467027,
}
trace_state={"a": "b", "c": "d"},
span_id=10217189687419569865,
trace_id=67545097771067222548457157018666467027,
),
resource=SDKResource({"a": 1, "b": False}),
parent=Mock(**{"span_id": 12345}),
parent=Mock(span_id=12345),
attributes=BoundedAttributes(attributes={"a": 1, "b": True}),
events=[event_mock],
links=[
Expand All @@ -117,14 +111,12 @@ def setUp(self):
self.span2 = _Span(
"b",
context=Mock(
**{
"trace_state": {"a": "b", "c": "d"},
"span_id": 10217189687419569865,
"trace_id": 67545097771067222548457157018666467027,
}
trace_state={"a": "b", "c": "d"},
span_id=10217189687419569865,
trace_id=67545097771067222548457157018666467027,
),
resource=SDKResource({"a": 2, "b": False}),
parent=Mock(**{"span_id": 12345}),
parent=Mock(span_id=12345),
instrumentation_scope=InstrumentationScope(
name="name", version="version"
),
Expand All @@ -133,14 +125,12 @@ def setUp(self):
self.span3 = _Span(
"c",
context=Mock(
**{
"trace_state": {"a": "b", "c": "d"},
"span_id": 10217189687419569865,
"trace_id": 67545097771067222548457157018666467027,
}
trace_state={"a": "b", "c": "d"},
span_id=10217189687419569865,
trace_id=67545097771067222548457157018666467027,
),
resource=SDKResource({"a": 1, "b": False}),
parent=Mock(**{"span_id": 12345}),
parent=Mock(span_id=12345),
instrumentation_scope=InstrumentationScope(
name="name2", version="version2"
),
Expand Down Expand Up @@ -784,13 +774,11 @@ def _create_span_with_status(status: SDKStatus):
span = _Span(
"a",
context=Mock(
**{
"trace_state": {"a": "b", "c": "d"},
"span_id": 10217189687419569865,
"trace_id": 67545097771067222548457157018666467027,
}
trace_state={"a": "b", "c": "d"},
span_id=10217189687419569865,
trace_id=67545097771067222548457157018666467027,
),
parent=Mock(**{"span_id": 12345}),
parent=Mock(span_id=12345),
instrumentation_scope=InstrumentationScope(
name="name", version="version"
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
_load_session_from_envvar,
)
from opentelemetry.metrics import MeterProvider
from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ( # noqa: F401
from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import (
ExportMetricsServiceRequest,
)
from opentelemetry.proto.common.v1.common_pb2 import ( # noqa: F401
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,9 @@
BASIC_SPAN = _Span(
"abc",
context=Mock(
**{
"trace_state": {"a": "b", "c": "d"},
"span_id": 10217189687419569865,
"trace_id": 67545097771067222548457157018666467027,
}
trace_state={"a": "b", "c": "d"},
span_id=10217189687419569865,
trace_id=67545097771067222548457157018666467027,
),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ def _collect_data_points(
return label_keys, label_rows, values

# pylint: disable=no-self-use
def _check_value(self, value: int | float | str | Sequence) -> str:
def _check_value(self, value: float | str | Sequence) -> str:
"""Check the label value and return is appropriate representation"""
if not isinstance(value, str):
return dumps(value, default=str)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,8 @@ def get_data_for_max_tag_length_test(
span.set_attribute("tuple4", (2,) * 10)
span.set_attribute("tuple5", (True,) * 25)
span.set_attribute("tuple6", (True,) * 10)
span.set_attribute("range1", range(0, 25))
span.set_attribute("range2", range(0, 10))
span.set_attribute("range1", range(25))
span.set_attribute("range2", range(10))
span.set_attribute("empty_list", [])
span.set_attribute("none_list", ["hello", None, "world"])
span.end(end_time=end_time)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,8 @@ def get_data_for_max_tag_length_test(
span.set_attribute("tuple4", (2,) * 10)
span.set_attribute("tuple5", (True,) * 25)
span.set_attribute("tuple6", (True,) * 10)
span.set_attribute("range1", range(0, 25))
span.set_attribute("range2", range(0, 10))
span.set_attribute("range1", range(25))
span.set_attribute("range2", range(10))
span.set_attribute("empty_list", [])
span.set_attribute("none_list", ["hello", None, "world"])
span.end(end_time=end_time)
Expand Down
Loading
Loading