Skip to content

Commit

Permalink
core: Add N(naming) ruff rules
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet committed Sep 17, 2024
1 parent 6ba3c71 commit bb91825
Show file tree
Hide file tree
Showing 38 changed files with 289 additions and 223 deletions.
4 changes: 2 additions & 2 deletions libs/core/langchain_core/_api/beta_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def warn_if_direct_instance(
_name = _name or obj.fget.__qualname__
old_doc = obj.__doc__

class _beta_property(property):
class _BetaProperty(property):
"""A beta property."""

def __init__(self, fget=None, fset=None, fdel=None, doc=None):
Expand Down Expand Up @@ -185,7 +185,7 @@ def __set_name__(self, owner, set_name):

def finalize(wrapper: Callable[..., Any], new_doc: str) -> Any:
"""Finalize the property."""
return _beta_property(
return _BetaProperty(
fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
)

Expand Down
4 changes: 2 additions & 2 deletions libs/core/langchain_core/_api/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
_name = _name or cast(Union[Type, Callable], obj.fget).__qualname__
old_doc = obj.__doc__

class _deprecated_property(property):
class _DeprecatedProperty(property):
"""A deprecated property."""

def __init__(self, fget=None, fset=None, fdel=None, doc=None): # type: ignore[no-untyped-def]
Expand Down Expand Up @@ -298,7 +298,7 @@ def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
"""Finalize the property."""
return cast(
T,
_deprecated_property(
_DeprecatedProperty(
fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
),
)
Expand Down
4 changes: 2 additions & 2 deletions libs/core/langchain_core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from typing import Any, Optional


class LangChainException(Exception):
class LangChainException(Exception): # noqa: N818
"""General LangChain exception."""


class TracerException(LangChainException):
"""Base class for exceptions in tracers module."""


class OutputParserException(ValueError, LangChainException):
class OutputParserException(ValueError, LangChainException): # noqa: N818
"""Exception that output parsers should raise to signify a parsing error.
This exists to differentiate parsing errors from other code or execution errors
Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/language_models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)

from pydantic import BaseModel, ConfigDict, Field, field_validator
from typing_extensions import TypeAlias, TypedDict
from typing_extensions import TypeAlias, TypedDict, override

from langchain_core._api import deprecated
from langchain_core.messages import (
Expand Down Expand Up @@ -148,6 +148,7 @@ def set_verbose(cls, verbose: Optional[bool]) -> bool:
return verbose

@property
@override
def InputType(self) -> TypeAlias:
"""Get the input type for this runnable."""
from langchain_core.prompt_values import (
Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/language_models/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
Field,
model_validator,
)
from typing_extensions import override

from langchain_core._api import deprecated
from langchain_core.caches import BaseCache
Expand Down Expand Up @@ -255,6 +256,7 @@ def _serialized(self) -> dict[str, Any]:
# --- Runnable methods ---

@property
@override
def OutputType(self) -> Any:
"""Get the output type for this runnable."""
return AnyMessage
Expand Down
2 changes: 2 additions & 0 deletions libs/core/langchain_core/language_models/llms.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
stop_after_attempt,
wait_exponential,
)
from typing_extensions import override

from langchain_core._api import deprecated
from langchain_core.caches import BaseCache
Expand Down Expand Up @@ -324,6 +325,7 @@ def _serialized(self) -> dict[str, Any]:
# --- Runnable methods ---

@property
@override
def OutputType(self) -> Type[str]:
"""Get the input type for this runnable."""
return str
Expand Down
6 changes: 6 additions & 0 deletions libs/core/langchain_core/output_parsers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
Union,
)

from typing_extensions import override

from langchain_core.language_models import LanguageModelOutput
from langchain_core.messages import AnyMessage, BaseMessage
from langchain_core.outputs import ChatGeneration, Generation
Expand Down Expand Up @@ -66,11 +68,13 @@ class BaseGenerationOutputParser(
"""Base class to parse the output of an LLM call."""

@property
@override
def InputType(self) -> Any:
"""Return the input type for the parser."""
return Union[str, AnyMessage]

@property
@override
def OutputType(self) -> Type[T]:
"""Return the output type for the parser."""
# even though mypy complains this isn't valid,
Expand Down Expand Up @@ -151,11 +155,13 @@ def _type(self) -> str:
""" # noqa: E501

@property
@override
def InputType(self) -> Any:
"""Return the input type for the parser."""
return Union[str, AnyMessage]

@property
@override
def OutputType(self) -> Type[T]:
"""Return the output type for the parser.
Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/output_parsers/pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import pydantic
from pydantic import SkipValidation
from typing_extensions import Annotated
from typing_extensions import Annotated, override

from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import JsonOutputParser
Expand Down Expand Up @@ -108,6 +108,7 @@ def _type(self) -> str:
return "pydantic"

@property
@override
def OutputType(self) -> Type[TBaseModel]:
"""Return the pydantic model."""
return self.pydantic_object
Expand Down
12 changes: 6 additions & 6 deletions libs/core/langchain_core/output_parsers/xml.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re
import xml
import xml.etree.ElementTree as ET
import xml.etree.ElementTree as ET # noqa: N817
from typing import Any, AsyncIterator, Dict, Iterator, List, Literal, Optional, Union
from xml.etree.ElementTree import TreeBuilder

Expand Down Expand Up @@ -45,14 +45,14 @@ def __init__(self, parser: Literal["defusedxml", "xml"]) -> None:
"""
if parser == "defusedxml":
try:
from defusedxml import ElementTree as DET # type: ignore
import defusedxml # type: ignore
except ImportError as e:
raise ImportError(
"defusedxml is not installed. "
"Please install it to use the defusedxml parser."
"You can install it with `pip install defusedxml` "
) from e
_parser = DET.DefusedXMLParser(target=TreeBuilder())
_parser = defusedxml.ElementTree.DefusedXMLParser(target=TreeBuilder())
else:
_parser = None
self.pull_parser = ET.XMLPullParser(["start", "end"], _parser=_parser)
Expand Down Expand Up @@ -188,17 +188,17 @@ def parse(self, text: str) -> Dict[str, Union[str, List[Any]]]:
# likely if you're reading this you can move them to the top of the file
if self.parser == "defusedxml":
try:
from defusedxml import ElementTree as DET # type: ignore
import defusedxml # type: ignore
except ImportError as e:
raise ImportError(
"defusedxml is not installed. "
"Please install it to use the defusedxml parser."
"You can install it with `pip install defusedxml`"
"See https://github.com/tiran/defusedxml for more details"
) from e
_ET = DET # Use the defusedxml parser
_et = defusedxml.ElementTree # Use the defusedxml parser
else:
_ET = ET # Use the standard library parser
_et = ET # Use the standard library parser

match = re.search(r"```(xml)?(.*)```", text, re.DOTALL)
if match is not None:
Expand Down
3 changes: 2 additions & 1 deletion libs/core/langchain_core/prompts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import yaml
from pydantic import BaseModel, ConfigDict, Field, model_validator
from typing_extensions import Self
from typing_extensions import Self, override

from langchain_core.load import dumpd
from langchain_core.output_parsers.base import BaseOutputParser
Expand Down Expand Up @@ -109,6 +109,7 @@ def _serialized(self) -> dict[str, Any]:
return dumpd(self)

@property
@override
def OutputType(self) -> Any:
"""Return the output type of the prompt."""
return Union[StringPromptValue, ChatPromptValueConcrete]
Expand Down
17 changes: 14 additions & 3 deletions libs/core/langchain_core/runnables/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
)

from pydantic import BaseModel, ConfigDict, Field, RootModel
from typing_extensions import Literal, get_args, get_type_hints
from typing_extensions import Literal, get_args, get_type_hints, override

from langchain_core._api import beta_decorator
from langchain_core.load.serializable import (
Expand Down Expand Up @@ -273,7 +273,7 @@ def get_name(
return name_

@property
def InputType(self) -> Type[Input]:
def InputType(self) -> Type[Input]: # noqa: N802
"""The type of input this Runnable accepts specified as a type annotation."""
# First loop through all parent classes and if any of them is
# a pydantic model, we will pick up the generic parameterization
Expand All @@ -298,7 +298,7 @@ def InputType(self) -> Type[Input]:
)

@property
def OutputType(self) -> Type[Output]:
def OutputType(self) -> Type[Output]: # noqa: N802
"""The type of output this Runnable produces specified as a type annotation."""
# First loop through bases -- this will help generic
# any pydantic models.
Expand Down Expand Up @@ -2804,11 +2804,13 @@ def is_lc_serializable(cls) -> bool:
)

@property
@override
def InputType(self) -> Type[Input]:
"""The type of the input to the Runnable."""
return self.first.InputType

@property
@override
def OutputType(self) -> Type[Output]:
"""The type of the output of the Runnable."""
return self.last.OutputType
Expand Down Expand Up @@ -3557,6 +3559,7 @@ def get_name(
return super().get_name(suffix, name=name)

@property
@override
def InputType(self) -> Any:
"""The type of the input to the Runnable."""
for step in self.steps__.values():
Expand Down Expand Up @@ -4050,6 +4053,7 @@ def __init__(
self.name = "RunnableGenerator"

@property
@override
def InputType(self) -> Any:
func = getattr(self, "_transform", None) or self._atransform
try:
Expand Down Expand Up @@ -4086,6 +4090,7 @@ def get_input_schema(
)

@property
@override
def OutputType(self) -> Any:
func = getattr(self, "_transform", None) or self._atransform
try:
Expand Down Expand Up @@ -4331,6 +4336,7 @@ def __init__(
pass

@property
@override
def InputType(self) -> Any:
"""The type of the input to this Runnable."""
func = getattr(self, "func", None) or self.afunc
Expand Down Expand Up @@ -4390,6 +4396,7 @@ def get_input_schema(
return super().get_input_schema(config)

@property
@override
def OutputType(self) -> Any:
"""The type of the output of this Runnable as a type annotation.
Expand Down Expand Up @@ -4939,6 +4946,7 @@ class RunnableEachBase(RunnableSerializable[List[Input], List[Output]]):
)

@property
@override
def InputType(self) -> Any:
return List[self.bound.InputType] # type: ignore[name-defined]

Expand All @@ -4962,6 +4970,7 @@ def get_input_schema(
)

@property
@override
def OutputType(self) -> Type[List[Output]]:
return List[self.bound.OutputType] # type: ignore[name-defined]

Expand Down Expand Up @@ -5255,6 +5264,7 @@ def get_name(
return self.bound.get_name(suffix, name=name)

@property
@override
def InputType(self) -> Type[Input]:
return (
cast(Type[Input], self.custom_input_type)
Expand All @@ -5263,6 +5273,7 @@ def InputType(self) -> Type[Input]:
)

@property
@override
def OutputType(self) -> Type[Output]:
return (
cast(Type[Output], self.custom_output_type)
Expand Down
3 changes: 3 additions & 0 deletions libs/core/langchain_core/runnables/configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from weakref import WeakValueDictionary

from pydantic import BaseModel, ConfigDict
from typing_extensions import override

from langchain_core.runnables.base import Runnable, RunnableSerializable
from langchain_core.runnables.config import (
Expand Down Expand Up @@ -74,10 +75,12 @@ def get_lc_namespace(cls) -> List[str]:
return ["langchain", "schema", "runnable"]

@property
@override
def InputType(self) -> Type[Input]:
return self.default.InputType

@property
@override
def OutputType(self) -> Type[Output]:
return self.default.OutputType

Expand Down
3 changes: 3 additions & 0 deletions libs/core/langchain_core/runnables/fallbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
)

from pydantic import BaseModel, ConfigDict
from typing_extensions import override

from langchain_core.runnables.base import Runnable, RunnableSerializable
from langchain_core.runnables.config import (
Expand Down Expand Up @@ -112,10 +113,12 @@ def when_all_is_lost(inputs):
)

@property
@override
def InputType(self) -> Type[Input]:
return self.runnable.InputType

@property
@override
def OutputType(self) -> Type[Output]:
return self.runnable.OutputType

Expand Down
Loading

0 comments on commit bb91825

Please sign in to comment.