Silence some pylint4 warnings (#4272)

* pylint: use unnecessary-dunder-call instead of E1101

Since pylint 4 now raises a different error code

* opentelemetry-instrumentation-sqlite3: fix pylint warnings

Possibly using variable 'root_span' before assignment (possibly-used-before-assignment)
Possibly using variable 'child_span' before assignment (possibly-used-before-assignment)

* opentelemetry-instrumentation-botocore: silence a bunch of pylint warnings

In the form of
Possibly using variable '<var>' before assignment (possibly-used-before-assignment)

* opentelemetry-instrumentation-redis: remove useless return spotted by pylint

* opentelemetry-instrumentation-fastapi: silence some pylint warnings

E0102: function already defined line 2034 (function-redefined)

* opentelemetry-instrumentation-google-genai: fix pylint warnings

Assisted by Cursor.

* opentelemetry-instrumentation-openai-v2: fix pylint 4 errors

Assisted by Cursor

* opentelemetry-instrumentation-elasticsearch: fix pylint 4 errors

Assisted by Cursor.

* opentelemetry-instrumentation-pika: fix pylint 4 errors

Assisted by cursor.

* opentelemetry-instrumentation-starlette: fix pylint 4 errors

* opentelemetry-instrumentation: fix pylint 4 errors

Assisted by Cursor.

* opentelemetry-util-http: fix pylint 4 errors
This commit is contained in:
Riccardo Magliocchetti
2026-03-12 11:07:32 +01:00
committed by GitHub
parent d01b7bf0b6
commit b35be0d73e
20 changed files with 98 additions and 37 deletions

View File

@@ -124,8 +124,7 @@ class TestCase(CommonTestCaseBase):
mock = unittest.mock.MagicMock()
def _default_impl(*args, **kwargs):
for response in self._responses:
yield response
yield from self._responses
if not e:
mock.side_effect = _default_impl

View File

@@ -418,6 +418,9 @@ async def test_chat_completion_with_raw_response_streaming(
response = raw_response.parse()
message_content = ""
response_stream_usage = None
response_stream_model = None
response_stream_id = None
async for chunk in response:
if chunk.choices:
message_content += chunk.choices[0].delta.content or ""
@@ -983,6 +986,9 @@ async def test_async_chat_completion_multiple_choices_streaming(
stream_options={"include_usage": True},
)
response_stream_usage = None
response_stream_model = None
response_stream_id = None
# two strings for each choice
response_stream_result = ["", ""]
finish_reasons = ["", ""]
@@ -1203,6 +1209,9 @@ async def async_chat_completion_multiple_tools_streaming(
)
finish_reason = None
response_stream_usage = None
response_stream_model = None
response_stream_id = None
# two tools
tool_names = ["", ""]
tool_call_ids = ["", ""]

View File

@@ -561,6 +561,9 @@ def test_chat_completion_with_raw_response_streaming(
response = raw_response.parse()
message_content = ""
response_stream_usage = None
response_stream_model = None
response_stream_id = None
for chunk in response:
if chunk.choices:
message_content += chunk.choices[0].delta.content or ""
@@ -1083,6 +1086,9 @@ def test_chat_completion_multiple_choices_streaming(
# two strings for each choice
response_stream_result = ["", ""]
finish_reasons = ["", ""]
response_stream_usage = None
response_stream_model = None
response_stream_id = None
for chunk in response_0:
if chunk.choices:
for choice in chunk.choices:
@@ -1274,6 +1280,9 @@ def test_chat_completion_with_context_manager_streaming(
stream_options={"include_usage": True},
) as response:
message_content = ""
response_stream_usage = None
response_stream_model = None
response_stream_id = None
for chunk in response:
if chunk.choices:
message_content += chunk.choices[0].delta.content or ""
@@ -1345,6 +1354,9 @@ def chat_completion_multiple_tools_streaming(
)
finish_reason = None
response_stream_usage = None
response_stream_model = None
response_stream_id = None
# two tools
tool_names = ["", ""]
tool_call_ids = ["", ""]

View File

@@ -1485,7 +1485,12 @@ def test_invoke_model_with_content(
"content": "\n\nA man stands before a crowd of people",
}
finish_reason = "length"
else:
pytest.xfail("model family not handled: {model_family}")
return
assert_message_in_logs(logs[0], "gen_ai.user.message", user_content, span)
choice_body = {
"index": 0,
"finish_reason": finish_reason,
@@ -1621,6 +1626,9 @@ def test_invoke_model_with_content_different_events(
system = anthropic_claude_system()
finish_reason = "end_turn"
choice_content = [{"type": "text", "text": "This is a test"}]
else:
pytest.xfail("llm_model_value not handled: {llm_model_value}")
return
body = get_invoke_model_body(
llm_model_value,
@@ -2060,6 +2068,9 @@ def test_invoke_model_with_content_tool_call(
elif model_family == "anthropic.claude":
llm_model_value = "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
llm_model_config = AnthropicClaudeModel
else:
pytest.xfail("model family not handled: {model_family}")
return
invoke_model_tool_call(
span_exporter,
@@ -2143,6 +2154,10 @@ def test_invoke_model_no_content(
elif model_family == "mistral.mistral":
choice_message = {}
finish_reason = "length"
else:
pytest.xfail("model family not handled: {model_family}")
return
choice_body = {
"index": 0,
"finish_reason": finish_reason,
@@ -2173,6 +2188,9 @@ def test_invoke_model_no_content_different_events(
messages = anthropic_claude_messages()
system = anthropic_claude_system()
finish_reason = "end_turn"
else:
pytest.xfail("llm_model_value not handled: {llm_model_value}")
return
body = get_invoke_model_body(
llm_model_value,
@@ -2226,6 +2244,9 @@ def test_invoke_model_no_content_tool_call(
elif model_family == "anthropic.claude":
llm_model_value = "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
llm_model_config = AnthropicClaudeModel
else:
pytest.xfail("model family not handled: {model_family}")
return
invoke_model_tool_call(
span_exporter,
@@ -2378,6 +2399,10 @@ def test_invoke_model_with_response_stream_with_content(
{"text": "\nHello! I am a computer program designed to"}
]
}
else:
pytest.xfail("model family not handled: {model_family}")
return
choice_body = {
"index": 0,
"finish_reason": finish_reason,
@@ -2410,6 +2435,9 @@ def test_invoke_model_with_response_stream_with_content_different_events(
system = anthropic_claude_system()
finish_reason = "end_turn"
choice_content = [{"text": "This is a test", "type": "text"}]
else:
pytest.xfail("llm_model_value not handled: {llm_model_value}")
return
max_tokens = 10
body = get_invoke_model_body(
@@ -2642,6 +2670,9 @@ def test_invoke_model_with_response_stream_with_content_tool_call(
elif model_family == "anthropic.claude":
llm_model_value = "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
llm_model_config = AnthropicClaudeModel
else:
pytest.xfail("model family not handled: {model_family}")
return
invoke_model_with_response_stream_tool_call(
span_exporter,
@@ -2768,6 +2799,9 @@ def test_invoke_model_with_response_stream_no_content_different_events(
messages = anthropic_claude_messages()
system = anthropic_claude_system()
finish_reason = "end_turn"
else:
pytest.xfail("llm_model_value not handled: {llm_model_value}")
return
max_tokens = 10
body = get_invoke_model_body(
@@ -2828,6 +2862,9 @@ def test_invoke_model_with_response_stream_no_content_tool_call(
elif model_family == "anthropic.claude":
llm_model_value = "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
llm_model_config = AnthropicClaudeModel
else:
pytest.xfail("model family not handled: {model_family}")
return
invoke_model_with_response_stream_tool_call(
span_exporter,

View File

@@ -182,7 +182,7 @@ class CeleryInstrumentor(BaseInstrumentor):
)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
utils.attach_context(task, task_id, span, activation, token)
def _trace_postrun(self, *args, **kwargs):
@@ -247,7 +247,7 @@ class CeleryInstrumentor(BaseInstrumentor):
utils.set_attributes_from_context(span, kwargs)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
utils.attach_context(
task, task_id, span, activation, None, is_publish=True
@@ -274,7 +274,7 @@ class CeleryInstrumentor(BaseInstrumentor):
_, activation, _ = ctx
activation.__exit__(None, None, None) # pylint: disable=E1101
activation.__exit__(None, None, None) # pylint: disable=unnecessary-dunder-call
utils.detach_context(task, task_id, is_publish=True)
@staticmethod

View File

@@ -271,7 +271,7 @@ class _DjangoMiddleware:
span.set_attribute(key, value)
activation = use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
request_start_time = default_timer()
request.META[self._environ_timer_key] = request_start_time
request.META[self._environ_activation_key] = activation

View File

@@ -42,6 +42,7 @@ from . import sanitization_queries # pylint: disable=no-name-in-module
major_version, minor_version = elasticsearch.VERSION[:2]
helpers = None
if major_version == 8:
from . import helpers_es8 as helpers # pylint: disable=no-name-in-module
elif major_version == 7:

View File

@@ -346,7 +346,7 @@ class _InstrumentedFalconAPI(getattr(falcon, _instrument_app)):
return super()._handle_exception(*args)
def __call__(self, env, start_response):
# pylint: disable=E1101
# pylint: disable=unnecessary-dunder-call
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
if self._otel_excluded_urls.url_disabled(env.get("PATH_INFO", "/")):

View File

@@ -238,27 +238,27 @@ class TestBaseFastAPI(TestBase):
custom_router = fastapi.APIRouter(route_class=CustomRoute)
@sub_app.get("/home")
async def _():
async def _home():
return {"message": "sub hi"}
@app.get("/foobar")
async def _():
async def _foobar():
return {"message": "hello world"}
@app.get("/user/{username}")
async def _(username: str):
async def _user(username: str):
return {"message": username}
@app.get("/exclude/{param}")
async def _(param: str):
async def _exclude(param: str):
return {"message": param}
@app.get("/healthzz")
async def _():
async def _health():
return {"message": "ok"}
@app.get("/error")
async def _():
async def _error():
raise UnhandledException("This is an unhandled exception")
@custom_router.get("/success")
@@ -1022,27 +1022,27 @@ class TestFastAPIManualInstrumentation(TestBaseManualFastAPI):
custom_router = fastapi.APIRouter(route_class=CustomRoute)
@sub_app.get("/home")
async def _():
async def _home():
return {"message": "sub hi"}
@app.get("/foobar")
async def _():
async def _foobar():
return {"message": "hello world"}
@app.get("/user/{username}")
async def _(username: str):
async def _user(username: str):
return {"message": username}
@app.get("/exclude/{param}")
async def _(param: str):
async def _exclude(param: str):
return {"message": param}
@app.get("/healthzz")
async def _():
async def _health():
return {"message": "ok"}
@app.get("/error")
async def _():
async def _error():
raise UnhandledException("This is an unhandled exception")
@custom_router.get("/success")
@@ -1965,7 +1965,7 @@ class TestTraceableExceptionHandling(TestBase):
return PlainTextResponse("", status_code)
@self.app.get("/foobar")
async def _():
async def _foobar():
self.request_trace_id = (
trace.get_current_span().get_span_context().trace_id
)
@@ -2032,7 +2032,7 @@ class TestTraceableExceptionHandling(TestBase):
"""Exceptions from user middlewares are recorded in the active span"""
@self.app.get("/foobar")
async def _():
async def _foobar():
return PlainTextResponse("Hello World")
@self.app.middleware("http")

View File

@@ -518,7 +518,7 @@ def _wrapped_before_request(
span.set_attributes(custom_attributes)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
flask_request_environ[_ENVIRON_ACTIVATION_KEY] = activation
flask_request_environ[_ENVIRON_REQCTX_REF_KEY] = _request_ctx_ref()
flask_request_environ[_ENVIRON_SPAN_KEY] = span
@@ -555,7 +555,7 @@ def _wrapped_teardown_request(
excluded_urls=None,
):
def _teardown_request(exc):
# pylint: disable=E1101
# pylint: disable=unnecessary-dunder-call
if excluded_urls and excluded_urls.url_disabled(flask.request.url):
return

View File

@@ -60,6 +60,7 @@ class PikaInstrumentor(BaseInstrumentor): # type: ignore
tracer: Tracer,
consume_hook: utils.HookT = utils.dummy_callback,
) -> Any:
consumer_infos = None
if isinstance(channel, BlockingChannel):
consumer_infos = channel._consumer_infos
elif isinstance(channel, Channel):

View File

@@ -148,7 +148,7 @@ def _before_traversal(event):
span.set_attributes(custom_attributes)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
request_environ[_ENVIRON_ACTIVATION_KEY] = activation
request_environ[_ENVIRON_SPAN_KEY] = span
if token:
@@ -212,7 +212,7 @@ def trace_tween_factory(handler, registry):
# make a request tracing function
# pylint: disable=too-many-branches
def trace_tween(request):
# pylint: disable=E1101, too-many-locals
# pylint: disable=unnecessary-dunder-call, too-many-locals
if _excluded_urls.url_disabled(request.url):
request.environ[_ENVIRON_ENABLED_KEY] = False
# short-circuit when we don't want to trace anything

View File

@@ -698,7 +698,6 @@ class RedisInstrumentor(BaseInstrumentor):
_logger.warning(
"Attempting to un-instrument Redis connection that wasn't instrumented"
)
return
def instrumentation_dependencies(self) -> Collection[str]:
"""Return a list of python packages with versions that the will be instrumented."""

View File

@@ -90,7 +90,7 @@ class _InstrumentationMiddleware(Middleware):
)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
utils.attach_span(
self._span_registry, message.message_id, (span, activation)
@@ -142,7 +142,7 @@ class _InstrumentationMiddleware(Middleware):
)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
utils.attach_span(
self._span_registry,

View File

@@ -54,6 +54,8 @@ class TestSQLite3(TestBase):
spans = self.memory_exporter.get_finished_spans()
self.memory_exporter.clear()
self.assertEqual(len(spans), 2)
root_span = None
child_span = None
for span in spans:
if span.name == "rootSpan":
root_span = span

View File

@@ -624,7 +624,7 @@ class TestBaseWithCustomHeaders(TestBase):
app = applications.Starlette()
@app.route("/foobar")
def _(request):
def _foobar(request):
return PlainTextResponse(
content="hi",
headers={
@@ -637,7 +637,7 @@ class TestBaseWithCustomHeaders(TestBase):
)
@app.websocket_route("/foobar_web")
async def _(websocket: WebSocket) -> None:
async def _foobar_web(websocket: WebSocket) -> None:
message = await websocket.receive()
if message.get("type") == "websocket.connect":
await websocket.send(

View File

@@ -776,7 +776,7 @@ def _start_span(tracer, handler, sem_conv_opt_in_mode) -> _TraceContext:
span.set_attributes(custom_attributes)
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
activation.__enter__() # pylint: disable=unnecessary-dunder-call
ctx = _TraceContext(activation, span, token)
setattr(handler, _HANDLER_CONTEXT_KEY, ctx)
@@ -829,7 +829,7 @@ def _finish_span(tracer, handler, error, sem_conv_opt_in_mode):
if len(custom_attributes) > 0:
ctx.span.set_attributes(custom_attributes)
ctx.activation.__exit__(*finish_args) # pylint: disable=E1101
ctx.activation.__exit__(*finish_args) # pylint: disable=unnecessary-dunder-call
if ctx.token:
context.detach(ctx.token)
delattr(handler, _HANDLER_CONTEXT_KEY)

View File

@@ -327,7 +327,7 @@ def set_int_attribute(
try:
result[key] = int(value)
except ValueError:
return
pass
def _set_http_method(

View File

@@ -117,8 +117,7 @@ def _is_installed(req):
def _find_installed_libraries(default_instrumentations, libraries):
for lib in default_instrumentations:
yield lib
yield from default_instrumentations
for lib in libraries:
if _is_installed(lib["library"]):

View File

@@ -95,6 +95,7 @@ def trysetip(
return True
sock = "<property not accessed>"
ip = None
try:
sock: typing.Optional[socket.socket] = conn.sock
logger.debug("Got socket: %s", sock)
@@ -112,8 +113,9 @@ def trysetip(
stack_info=True,
)
else:
for span in spanlist:
span.set_attribute(NET_PEER_IP, ip)
if ip is not None:
for span in spanlist:
span.set_attribute(NET_PEER_IP, ip)
return True