Skip to content

Commit f8155e1

Browse files
authored
chore: clean up (#9504)
1 parent 54c5057 commit f8155e1

11 files changed

Lines changed: 142 additions & 139 deletions

File tree

haystack/components/classifiers/document_language_classifier.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,11 @@ def run(self, documents: List[Document]):
9999
return {"documents": documents}
100100

101101
def _detect_language(self, document: Document) -> Optional[str]:
102+
language = None
102103
try:
103104
language = langdetect.detect(document.content)
104105
except langdetect.LangDetectException:
105106
logger.warning(
106107
"Langdetect cannot detect the language of Document with id: {document_id}", document_id=document.id
107108
)
108-
language = None
109109
return language

haystack/components/connectors/openapi_service.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -377,9 +377,8 @@ def _invoke_method(self, openapi_service: "OpenAPI", method_invocation_descripto
377377
param_value = invocation_arguments.get(param_name)
378378
if param_value:
379379
method_call_params["parameters"][param_name] = param_value
380-
else:
381-
if param.get("required", False):
382-
raise ValueError(f"Missing parameter: '{param_name}' required for the '{name}' operation.")
380+
elif param.get("required", False):
381+
raise ValueError(f"Missing parameter: '{param_name}' required for the '{name}' operation.")
383382

384383
# Pack request body parameters under "data" key
385384
if request_body:
@@ -389,10 +388,9 @@ def _invoke_method(self, openapi_service: "OpenAPI", method_invocation_descripto
389388
param_value = invocation_arguments.get(param_name)
390389
if param_value:
391390
method_call_params["data"][param_name] = param_value
392-
else:
393-
if param_name in required_params:
394-
raise ValueError(
395-
f"Missing requestBody parameter: '{param_name}' required for the '{name}' operation."
396-
)
391+
elif param_name in required_params:
392+
raise ValueError(
393+
f"Missing requestBody parameter: '{param_name}' required for the '{name}' operation."
394+
)
397395
# call the underlying service REST API with the parameters
398396
return method_to_call(**method_call_params, raw_response=True)

haystack/components/evaluators/llm_evaluator.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ def validate_input_parameters(expected: Dict[str, Any], received: Dict[str, Any]
322322
If the received inputs are not lists or have different lengths
323323
"""
324324
# Validate that all expected inputs are present in the received inputs
325-
for param in expected.keys():
325+
for param in expected:
326326
if param not in received:
327327
msg = f"LLM evaluator expected input parameter '{param}' but received only {received.keys()}."
328328
raise ValueError(msg)

haystack/components/extractors/llm_metadata_extractor.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,8 @@ def from_dict(cls, data: Dict[str, Any]) -> "LLMMetadataExtractor":
205205
return default_from_dict(cls, data)
206206

207207
def _extract_metadata(self, llm_answer: str) -> Dict[str, Any]:
208+
parsed_metadata: Dict[str, Any] = {}
209+
208210
try:
209211
parsed_metadata = json.loads(llm_answer)
210212
except json.JSONDecodeError as e:

haystack/components/routers/text_language_router.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,11 @@ def run(self, text: str) -> Dict[str, str]:
9292
return output
9393

9494
def _detect_language(self, text: str) -> Optional[str]:
95+
language = None
9596
try:
9697
language = langdetect.detect(text)
9798
except langdetect.LangDetectException as exception:
9899
logger.warning("Langdetect cannot detect the language of text. Error: {error}", error=exception)
99100
# Only log the text in debug mode, as it might contain sensitive information
100101
logger.debug("Langdetect cannot detect the language of text: {text}", text=text)
101-
language = None
102102
return language

haystack/core/serialization.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import inspect
66
from collections.abc import Callable
77
from dataclasses import dataclass
8-
from typing import Any, Dict, Iterable, Optional, Type
8+
from typing import Any, Dict, Iterable, Optional, Type, TypeVar
99

1010
from haystack import logging
1111
from haystack.core.component.component import _hook_component_init
@@ -14,6 +14,8 @@
1414

1515
logger = logging.getLogger(__name__)
1616

17+
T = TypeVar("T")
18+
1719

1820
@dataclass(frozen=True)
1921
class DeserializationCallbacks:
@@ -100,7 +102,7 @@ def check_iterable(l: Iterable[Any]) -> None:
100102
check_dict(v)
101103

102104
def check_dict(d: Dict[str, Any]) -> None:
103-
if any(not isinstance(k, str) for k in data.keys()):
105+
if any(not isinstance(k, str) for k in data):
104106
raise SerializationError(
105107
f"Component '{name}' of type '{type(component).__name__}' has a non-string key in the serialized data."
106108
)
@@ -210,7 +212,7 @@ def to_dict(self):
210212
return {"type": generate_qualified_class_name(type(obj)), "init_parameters": init_parameters}
211213

212214

213-
def default_from_dict(cls: Type[object], data: Dict[str, Any]) -> Any:
215+
def default_from_dict(cls: Type[T], data: Dict[str, Any]) -> T:
214216
"""
215217
Utility function to deserialize a dictionary to an object.
216218

haystack/tools/component_tool.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,7 @@ def _create_tool_parameters_schema(self, component: Component, inputs_from_state
291291
resolved_type = _resolve_type(input_type)
292292
fields[input_name] = (resolved_type, Field(default=default, description=description))
293293

294+
parameters_schema: Dict[str, Any] = {}
294295
try:
295296
model = create_model(component.run.__name__, __doc__=component_run_description, **fields)
296297
parameters_schema = model.model_json_schema()

haystack/utils/auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def to_dict(self) -> Dict[str, Any]:
8282
"""
8383
out = {"type": self.type.value}
8484
inner = self._to_dict()
85-
assert all(k not in inner for k in out.keys())
85+
assert all(k not in inner for k in out)
8686
out.update(inner)
8787
return out
8888

pyproject.toml

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -255,13 +255,13 @@ disable = [
255255
"deprecated-method",
256256
]
257257
[tool.pylint.'DESIGN']
258-
max-args = 38 # Default is 5
259-
max-attributes = 28 # Default is 7
260-
max-branches = 34 # Default is 12
261-
max-locals = 45 # Default is 15
262-
max-module-lines = 2468 # Default is 1000
263-
max-nested-blocks = 9 # Default is 5
264-
max-statements = 206 # Default is 50
258+
max-args = 20 # Default is 5
259+
max-attributes = 22 # Default is 7
260+
max-branches = 22 # Default is 12
261+
max-locals = 39 # Default is 15
262+
max-module-lines = 1500 # Default is 1000
263+
max-nested-blocks = 6 # Default is 5
264+
max-statements = 102 # Default is 50
265265

266266
[tool.pylint.'SIMILARITIES']
267267
min-similarity-lines = 6
@@ -285,7 +285,6 @@ asyncio_default_fixture_loop_scope = "class"
285285
python_version = "3.9"
286286
disallow_incomplete_defs = true
287287
warn_return_any = false
288-
warn_unused_configs = true
289288
ignore_missing_imports = true
290289
check_untyped_defs = true
291290

@@ -340,26 +339,23 @@ ignore = [
340339
"PERF203", # `try`-`except` within a loop incurs performance overhead
341340
"PERF401", # Use a list comprehension to create a transformed list
342341
"PLR1714", # repeated-equality-comparison
343-
"PLR5501", # collapsible-else-if
344342
"PLW0603", # global-statement
345-
"PLW1510", # subprocess-run-without-check
346343
"PLW2901", # redefined-loop-name
347344
"SIM108", # if-else-block-instead-of-if-exp
348-
"SIM115", # open-file-with-context-handler
349345
"SIM118", # in-dict-keys
350346
]
351347

352348
[tool.ruff.lint.mccabe]
353-
max-complexity = 28
349+
max-complexity = 20
354350

355351

356352
[tool.ruff.lint.pylint]
357353
allow-magic-value-types = ["float", "int", "str"]
358-
max-args = 14 # Default is 5
354+
max-args = 13 # Default is 5
359355
max-branches = 21 # Default is 12
360356
max-public-methods = 20 # Default is 20
361357
max-returns = 7 # Default is 6
362-
max-statements = 60 # Default is 50
358+
max-statements = 56 # Default is 50
363359

364360
[tool.coverage.run]
365361
omit = ["haystack/testing/*"]

0 commit comments

Comments
 (0)