core: Add ruff rules TRY (tryceratops) (#29388)

TRY004 ("use TypeError rather than ValueError") existing errors are
marked as ignore to preserve backward compatibility.
LMK if you prefer to fix some of them.

Co-authored-by: Erick Friis <erick@langchain.dev>
This commit is contained in:
Christophe Bornet
2025-01-24 06:01:40 +01:00
committed by GitHub
parent 723b603f52
commit dbb6b7b103
26 changed files with 138 additions and 126 deletions

View File

@@ -188,7 +188,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
last_error = e
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
else:
run_manager.on_chain_end(output)
return output
@@ -241,7 +241,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
last_error = e
except BaseException as e:
await run_manager.on_chain_error(e)
raise e
raise
else:
await run_manager.on_chain_end(output)
return output
@@ -488,7 +488,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
last_error = e
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
else:
first_error = None
break
@@ -507,7 +507,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
output = None
except BaseException as e:
run_manager.on_chain_error(e)
raise e
raise
run_manager.on_chain_end(output)
async def astream(
@@ -558,7 +558,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
last_error = e
except BaseException as e:
await run_manager.on_chain_error(e)
raise e
raise
else:
first_error = None
break
@@ -577,7 +577,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
output = None
except BaseException as e:
await run_manager.on_chain_error(e)
raise e
raise
await run_manager.on_chain_end(output)
def __getattr__(self, name: str) -> Any:

View File

@@ -50,9 +50,9 @@ def is_uuid(value: str) -> bool:
"""
try:
UUID(value)
return True
except ValueError:
return False
return True
class Edge(NamedTuple):

View File

@@ -481,7 +481,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):
f"Expected str, BaseMessage, List[BaseMessage], or Tuple[BaseMessage]. "
f"Got {input_val}."
)
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
def _get_output_messages(
self, output_val: Union[str, BaseMessage, Sequence[BaseMessage], dict]
@@ -517,7 +517,7 @@ class RunnableWithMessageHistory(RunnableBindingBase):
f"Expected str, BaseMessage, List[BaseMessage], or Tuple[BaseMessage]. "
f"Got {output_val}."
)
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
def _enter_history(self, input: Any, config: RunnableConfig) -> list[BaseMessage]:
hist: BaseChatMessageHistory = config["configurable"]["message_history"]

View File

@@ -474,7 +474,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
) -> dict[str, Any]:
if not isinstance(input, dict):
msg = "The input to RunnablePassthrough.assign() must be a dict."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return {
**input,
@@ -502,7 +502,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
) -> dict[str, Any]:
if not isinstance(input, dict):
msg = "The input to RunnablePassthrough.assign() must be a dict."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return {
**input,
@@ -555,7 +555,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
for chunk in for_passthrough:
if not isinstance(chunk, dict):
msg = "The input to RunnablePassthrough.assign() must be a dict."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
# remove mapper keys from passthrough chunk, to be overwritten by map
filtered = AddableDict(
{k: v for k, v in chunk.items() if k not in mapper_keys}
@@ -605,7 +605,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
async for chunk in for_passthrough:
if not isinstance(chunk, dict):
msg = "The input to RunnablePassthrough.assign() must be a dict."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
# remove mapper keys from passthrough chunk, to be overwritten by map output
filtered = AddableDict(
@@ -708,7 +708,7 @@ class RunnablePick(RunnableSerializable[dict[str, Any], dict[str, Any]]):
def _pick(self, input: dict[str, Any]) -> Any:
if not isinstance(input, dict):
msg = "The input to RunnablePassthrough.assign() must be a dict."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
if isinstance(self.keys, str):
return input.get(self.keys)

View File

@@ -397,9 +397,9 @@ def get_lambda_source(func: Callable) -> Optional[str]:
tree = ast.parse(textwrap.dedent(code))
visitor = GetLambdaSource()
visitor.visit(tree)
return visitor.source if visitor.count == 1 else name
except (SyntaxError, TypeError, OSError, SystemError):
return name
return visitor.source if visitor.count == 1 else name
@lru_cache(maxsize=256)
@@ -440,10 +440,11 @@ def get_function_nonlocals(func: Callable) -> list[Any]:
break
else:
values.append(vv)
return values
except (SyntaxError, TypeError, OSError, SystemError):
return []
return values
def indent_lines_after_first(text: str, prefix: str) -> str:
"""Indent all lines of text after the first line.