Skip to content

Commit b28a474

Browse files
cborneteyurtsev
andauthored
core[patch]: Add ruff rules for PLW (Pylint Warnings) (#29288)
See https://docs.astral.sh/ruff/rules/#warning-w_1 --------- Co-authored-by: Eugene Yurtsev <[email protected]>
1 parent 75823d5 commit b28a474

File tree

10 files changed

+43
-32
lines changed

10 files changed

+43
-32
lines changed

libs/core/langchain_core/messages/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ def filter_messages(
504504
)
505505
]
506506

507-
msg = msg.model_copy(
507+
msg = msg.model_copy( # noqa: PLW2901
508508
update={"tool_calls": tool_calls, "content": content}
509509
)
510510
elif (

libs/core/langchain_core/output_parsers/json.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -125,5 +125,11 @@ def _type(self) -> str:
125125

126126
# For backwards compatibility
127127
SimpleJsonOutputParser = JsonOutputParser
128-
parse_partial_json = parse_partial_json
129-
parse_and_check_json_markdown = parse_and_check_json_markdown
128+
129+
130+
__all__ = [
131+
"JsonOutputParser",
132+
"SimpleJsonOutputParser", # For backwards compatibility
133+
"parse_partial_json", # For backwards compatibility
134+
"parse_and_check_json_markdown", # For backwards compatibility
135+
]

libs/core/langchain_core/output_parsers/list.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,10 @@ def _transform(
7373
chunk_content = chunk.content
7474
if not isinstance(chunk_content, str):
7575
continue
76-
chunk = chunk_content
77-
# add current chunk to buffer
78-
buffer += chunk
76+
buffer += chunk_content
77+
else:
78+
# add current chunk to buffer
79+
buffer += chunk
7980
# parse buffer into a list of parts
8081
try:
8182
done_idx = 0
@@ -105,9 +106,10 @@ async def _atransform(
105106
chunk_content = chunk.content
106107
if not isinstance(chunk_content, str):
107108
continue
108-
chunk = chunk_content
109-
# add current chunk to buffer
110-
buffer += chunk
109+
buffer += chunk_content
110+
else:
111+
# add current chunk to buffer
112+
buffer += chunk
111113
# parse buffer into a list of parts
112114
try:
113115
done_idx = 0

libs/core/langchain_core/tracers/evaluation.py

-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929

3030
def wait_for_all_evaluators() -> None:
3131
"""Wait for all tracers to finish."""
32-
global _TRACERS
3332
for tracer in list(_TRACERS):
3433
if tracer is not None:
3534
tracer.wait_for_futures()
@@ -100,7 +99,6 @@ def __init__(
10099
self.project_name = project_name
101100
self.logged_eval_results: dict[tuple[str, str], list[EvaluationResult]] = {}
102101
self.lock = threading.Lock()
103-
global _TRACERS
104102
_TRACERS.add(self)
105103

106104
def _evaluate_in_project(self, run: Run, evaluator: langsmith.RunEvaluator) -> None:

libs/core/langchain_core/tracers/langchain.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ def log_error_once(method: str, exception: Exception) -> None:
4141
method: The method that raised the exception.
4242
exception: The exception that was raised.
4343
"""
44-
global _LOGGED
4544
if (method, type(exception)) in _LOGGED:
4645
return
4746
_LOGGED.add((method, type(exception)))
@@ -61,7 +60,7 @@ def get_client() -> Client:
6160

6261
def _get_executor() -> ThreadPoolExecutor:
6362
"""Get the executor."""
64-
global _EXECUTOR
63+
global _EXECUTOR # noqa: PLW0603
6564
if _EXECUTOR is None:
6665
_EXECUTOR = ThreadPoolExecutor()
6766
return _EXECUTOR

libs/core/langchain_core/utils/_merge.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,12 @@ def merge_lists(left: Optional[list], *others: Optional[list]) -> Optional[list]
9696
if to_merge:
9797
# TODO: Remove this once merge_dict is updated with special
9898
# handling for 'type'.
99-
if "type" in e:
100-
e = {k: v for k, v in e.items() if k != "type"}
101-
merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e)
99+
new_e = (
100+
{k: v for k, v in e.items() if k != "type"}
101+
if "type" in e
102+
else e
103+
)
104+
merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], new_e)
102105
else:
103106
merged.append(e)
104107
else:

libs/core/langchain_core/utils/json.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,14 @@ def parse_partial_json(s: str, *, strict: bool = False) -> Any:
6464

6565
# Process each character in the string one at a time.
6666
for char in s:
67+
new_char = char
6768
if is_inside_string:
6869
if char == '"' and not escaped:
6970
is_inside_string = False
7071
elif char == "\n" and not escaped:
71-
char = "\\n" # Replace the newline character with the escape sequence.
72+
new_char = (
73+
"\\n" # Replace the newline character with the escape sequence.
74+
)
7275
elif char == "\\":
7376
escaped = not escaped
7477
else:
@@ -89,7 +92,7 @@ def parse_partial_json(s: str, *, strict: bool = False) -> Any:
8992
return None
9093

9194
# Append the processed character to the new string.
92-
new_chars.append(char)
95+
new_chars.append(new_char)
9396

9497
# If we're still inside a string at the end of processing,
9598
# we need to close the string.

libs/core/langchain_core/utils/mustache.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,6 @@ def parse_tag(template: str, l_del: str, r_del: str) -> tuple[tuple[str, str], s
125125
ChevronError: If the tag is unclosed.
126126
ChevronError: If the set delimiter tag is unclosed.
127127
"""
128-
global _CURRENT_LINE, _LAST_TAG_LINE
129-
130128
tag_types = {
131129
"!": "comment",
132130
"#": "section",
@@ -352,32 +350,33 @@ def _get_key(
352350
if scope in (0, False):
353351
return scope
354352

353+
resolved_scope = scope
355354
# For every dot separated key
356355
for child in key.split("."):
357356
# Return an empty string if falsy, with two exceptions
358357
# 0 should return 0, and False should return False
359-
if scope in (0, False):
360-
return scope
358+
if resolved_scope in (0, False):
359+
return resolved_scope
361360
# Move into the scope
362361
try:
363362
# Try subscripting (Normal dictionaries)
364-
scope = cast(dict[str, Any], scope)[child]
363+
resolved_scope = cast(dict[str, Any], resolved_scope)[child]
365364
except (TypeError, AttributeError):
366365
try:
367-
scope = getattr(scope, child)
366+
resolved_scope = getattr(resolved_scope, child)
368367
except (TypeError, AttributeError):
369368
# Try as a list
370-
scope = scope[int(child)] # type: ignore
369+
resolved_scope = resolved_scope[int(child)] # type: ignore
371370

372371
try:
373372
# This allows for custom falsy data types
374373
# https://github.com/noahmorrison/chevron/issues/35
375-
if scope._CHEVRON_return_scope_when_falsy: # type: ignore
376-
return scope
374+
if resolved_scope._CHEVRON_return_scope_when_falsy: # type: ignore
375+
return resolved_scope
377376
except AttributeError:
378-
if scope in (0, False):
379-
return scope
380-
return scope or ""
377+
if resolved_scope in (0, False):
378+
return resolved_scope
379+
return resolved_scope or ""
381380
except (AttributeError, KeyError, IndexError, ValueError):
382381
# We couldn't find the key in the current scope
383382
# We'll try again on the next pass

libs/core/pyproject.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ target-version = "py39"
7777

7878

7979
[tool.ruff.lint]
80-
select = [ "ANN", "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "PTH", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TC", "TID", "TRY", "UP", "W", "YTT",]
80+
select = [ "ANN", "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "PLW", "PTH", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TC", "TID", "TRY", "UP", "W", "YTT",]
8181
ignore = [ "ANN401", "COM812", "UP007", "S110", "S112", "TC001", "TC002", "TC003"]
8282
flake8-type-checking.runtime-evaluated-base-classes = ["pydantic.BaseModel","langchain_core.load.serializable.Serializable","langchain_core.runnables.base.RunnableSerializable"]
8383
flake8-annotations.allow-star-arg-any = true
@@ -96,6 +96,7 @@ filterwarnings = [ "ignore::langchain_core._api.beta_decorator.LangChainBetaWarn
9696
classmethod-decorators = [ "classmethod", "langchain_core.utils.pydantic.pre_init", "pydantic.field_validator", "pydantic.v1.root_validator",]
9797

9898
[tool.ruff.lint.per-file-ignores]
99+
"langchain_core/utils/mustache.py" = [ "PLW0603",]
99100
"tests/unit_tests/prompts/test_chat.py" = [ "E501",]
100101
"tests/unit_tests/runnables/test_runnable.py" = [ "E501",]
101102
"tests/unit_tests/runnables/test_graph.py" = [ "E501",]

libs/core/tests/unit_tests/test_imports.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def try_to_import(module_name: str) -> tuple[int, str]:
2222
getattr(module, cls_)
2323

2424
result = subprocess.run(
25-
["python", "-c", f"import langchain_core.{module_name}"],
25+
["python", "-c", f"import langchain_core.{module_name}"], check=True
2626
)
2727
return result.returncode, module_name
2828

0 commit comments

Comments
 (0)