Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: Add ruff rules ANN (type annotations) #29271

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
18 changes: 13 additions & 5 deletions libs/core/langchain_core/_api/beta_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,28 +157,36 @@ def warn_if_direct_instance(
class _BetaProperty(property):
"""A beta property."""

def __init__(self, fget=None, fset=None, fdel=None, doc=None):
def __init__(
self,
fget: Callable[[Any], Any] | None = None,
fset: Callable[[Any, Any], None] | None = None,
fdel: Callable[[Any], None] | None = None,
doc: str | None = None,
) -> None:
super().__init__(fget, fset, fdel, doc)
self.__orig_fget = fget
self.__orig_fset = fset
self.__orig_fdel = fdel

def __get__(self, instance, owner=None):
def __get__(
self, instance: Any, owner: Union[type, None] = None
) -> Any:
if instance is not None or owner is not None:
emit_warning()
return self.fget(instance)

def __set__(self, instance, value):
def __set__(self, instance: Any, value: Any) -> None:
if instance is not None:
emit_warning()
return self.fset(instance, value)

def __delete__(self, instance):
def __delete__(self, instance: Any) -> None:
if instance is not None:
emit_warning()
return self.fdel(instance)

def __set_name__(self, owner, set_name):
def __set_name__(self, owner: Union[type, None], set_name: str) -> None:
nonlocal _name
if _name == "<lambda>":
_name = set_name
Expand Down
26 changes: 19 additions & 7 deletions libs/core/langchain_core/_api/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,28 +271,40 @@ def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
class _DeprecatedProperty(property):
"""A deprecated property."""

def __init__(self, fget=None, fset=None, fdel=None, doc=None): # type: ignore[no-untyped-def]
def __init__(
self,
fget: Callable[[Any], Any] | None = None,
fset: Callable[[Any, Any], None] | None = None,
fdel: Callable[[Any], None] | None = None,
doc: str | None = None,
) -> None:
super().__init__(fget, fset, fdel, doc)
self.__orig_fget = fget
self.__orig_fset = fset
self.__orig_fdel = fdel

def __get__(self, instance, owner=None): # type: ignore[no-untyped-def]
def __get__(
self, instance: Any, owner: Union[type, None] = None
) -> Any:
if instance is not None or owner is not None:
emit_warning()
if self.fget is None:
Copy link
Collaborator Author

@cbornet cbornet Jan 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Other possibility could be to call super().__get__ ?

return None
return self.fget(instance)

def __set__(self, instance, value): # type: ignore[no-untyped-def]
def __set__(self, instance: Any, value: Any) -> None:
if instance is not None:
emit_warning()
return self.fset(instance, value)
if self.fset is not None:
self.fset(instance, value)

def __delete__(self, instance): # type: ignore[no-untyped-def]
def __delete__(self, instance: Any) -> None:
if instance is not None:
emit_warning()
return self.fdel(instance)
if self.fdel is not None:
self.fdel(instance)

def __set_name__(self, owner, set_name): # type: ignore[no-untyped-def]
def __set_name__(self, owner: Union[type, None], set_name: str) -> None:
nonlocal _name
if _name == "<lambda>":
_name = set_name
Expand Down
4 changes: 2 additions & 2 deletions libs/core/langchain_core/runnables/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4631,7 +4631,7 @@ def func(
)

@wraps(func)
async def f(*args, **kwargs): # type: ignore[no-untyped-def]
async def f(*args: Any, **kwargs: Any) -> Any:
return await run_in_executor(config, func, *args, **kwargs)

afunc = f
Expand Down Expand Up @@ -4880,7 +4880,7 @@ def func(
)

@wraps(func)
async def f(*args, **kwargs): # type: ignore[no-untyped-def]
async def f(*args: Any, **kwargs: Any) -> Any:
return await run_in_executor(config, func, *args, **kwargs)

afunc = f
Expand Down
8 changes: 4 additions & 4 deletions libs/core/langchain_core/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import importlib
import os
import warnings
from collections.abc import Sequence
from collections.abc import Iterator, Sequence
from importlib.metadata import version
from typing import Any, Callable, Optional, Union, overload

Expand Down Expand Up @@ -73,7 +73,7 @@ def raise_for_status_with_text(response: Response) -> None:


@contextlib.contextmanager
def mock_now(dt_value): # type: ignore
def mock_now(dt_value: datetime.datetime) -> Iterator[type]:
"""Context manager for mocking out datetime.now() in unit tests.

Args:
Expand All @@ -91,9 +91,9 @@ class MockDateTime(datetime.datetime):
"""Mock datetime.datetime.now() with a fixed datetime."""

@classmethod
def now(cls): # type: ignore
def now(cls, tz: datetime.tzinfo | None = None) -> "MockDateTime":
# Create a copy of dt_value.
return datetime.datetime(
return MockDateTime(
dt_value.year,
dt_value.month,
dt_value.day,
Expand Down
7 changes: 5 additions & 2 deletions libs/core/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ python = ">=3.12.4"
[tool.poetry.extras]

[tool.ruff.lint]
select = [ "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TID", "UP", "W", "YTT",]
ignore = [ "COM812", "UP007", "W293", "S101", "S110", "S112",]
select = [ "ANN", "ASYNC", "B", "C4", "COM", "DJ", "E", "EM", "EXE", "F", "FLY", "FURB", "I", "ICN", "INT", "LOG", "N", "NPY", "PD", "PIE", "Q", "RSE", "S", "SIM", "SLOT", "T10", "T201", "TID", "UP", "W", "YTT",]
ignore = [ "ANN101", "ANN102", "ANN401", "COM812", "S101", "S110", "S112", "UP007", "W293",]

flake8-annotations.allow-star-arg-any = true
flake8-annotations.mypy-init-return = true

[tool.coverage.run]
omit = [ "tests/*",]
Expand Down
6 changes: 3 additions & 3 deletions libs/core/tests/unit_tests/runnables/test_runnable.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ def test_lambda_schemas(snapshot: SnapshotAssertion) -> None:
"required": ["bye", "hello"],
}

def get_value(input): # type: ignore[no-untyped-def]
def get_value(input): # type: ignore[no-untyped-def] # noqa: ANN001,ANN202
return input["variable_name"]

assert RunnableLambda(get_value).get_input_jsonschema() == {
Expand All @@ -576,7 +576,7 @@ def get_value(input): # type: ignore[no-untyped-def]
"required": ["variable_name"],
}

async def aget_value(input): # type: ignore[no-untyped-def]
async def aget_value(input): # type: ignore[no-untyped-def] # noqa: ANN001,ANN202
return (input["variable_name"], input.get("another"))

assert RunnableLambda(aget_value).get_input_jsonschema() == {
Expand All @@ -589,7 +589,7 @@ async def aget_value(input): # type: ignore[no-untyped-def]
"required": ["another", "variable_name"],
}

async def aget_values(input): # type: ignore[no-untyped-def]
async def aget_values(input): # type: ignore[no-untyped-def] # noqa: ANN001,ANN202
return {
"hello": input["variable_name"],
"bye": input["variable_name"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from itertools import cycle
from typing import (
Any,
Callable,
Optional,
cast,
)
Expand Down Expand Up @@ -1889,10 +1890,10 @@ def get_by_session_id(session_id: str) -> BaseChatMessageHistory:
# so we can raise them in this main thread
raised_errors = []

def collect_errors(fn): # type: ignore
def collect_errors(fn: Callable[..., Any]) -> Callable[..., Any]:
nonlocal raised_errors

def _get_output_messages(*args, **kwargs): # type: ignore
def _get_output_messages(*args: Any, **kwargs: Any) -> Any:
try:
return fn(*args, **kwargs)
except Exception as e:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def parent() -> str:
else:

@RunnableLambda
def parent(_) -> str: # type: ignore
def parent(_: Any) -> str:
return child.invoke("foo")

tracer = LangChainTracer()
Expand Down
2 changes: 1 addition & 1 deletion libs/core/tests/unit_tests/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2186,7 +2186,7 @@ class Foo(BaseModelV2):
)

@tool(args_schema=Foo)
def foo(x): # type: ignore[no-untyped-def]
def foo(x: list[int]) -> list[int]:
"""foo"""
return x

Expand Down
Loading