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 Aug 14, 2024
1 parent 9d08369 commit 294d98c
Show file tree
Hide file tree
Showing 35 changed files with 266 additions and 200 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 @@ -236,7 +236,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 @@ -269,7 +269,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 @@ -17,7 +17,7 @@
Union,
)

from typing_extensions import TypeAlias
from typing_extensions import TypeAlias, override

from langchain_core._api import deprecated
from langchain_core.messages import (
Expand Down Expand Up @@ -126,6 +126,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
3 changes: 2 additions & 1 deletion libs/core/langchain_core/language_models/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
cast,
)

from typing_extensions import TypedDict
from typing_extensions import TypedDict, override

from langchain_core._api import deprecated
from langchain_core.caches import BaseCache
Expand Down Expand Up @@ -260,6 +260,7 @@ class Config:
# --- 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 @@ -36,6 +36,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 @@ -314,6 +315,7 @@ def raise_deprecation(cls, values: Dict) -> Dict:
# --- Runnable methods ---

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

from typing_extensions import get_args
from typing_extensions import get_args, override

from langchain_core.language_models import LanguageModelOutput
from langchain_core.messages import AnyMessage, BaseMessage
Expand Down Expand Up @@ -68,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 @@ -153,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
2 changes: 2 additions & 0 deletions libs/core/langchain_core/output_parsers/pydantic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Generic, List, Type

import pydantic # pydantic: ignore
from typing_extensions import override

from langchain_core.exceptions import OutputParserException
from langchain_core.output_parsers import JsonOutputParser
Expand Down Expand Up @@ -101,6 +102,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:
raise ImportError(
"defusedxml is not installed. "
"Please install it to use the defusedxml parser."
"You can install it with `pip install defusedxml` "
)
_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:
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"
)
_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
2 changes: 2 additions & 0 deletions libs/core/langchain_core/prompts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
)

import yaml
from typing_extensions import override

from langchain_core.output_parsers.base import BaseOutputParser
from langchain_core.prompt_values import (
Expand Down Expand Up @@ -103,6 +104,7 @@ class Config:
arbitrary_types_allowed = True

@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 @@ -35,7 +35,7 @@
overload,
)

from typing_extensions import Literal, get_args
from typing_extensions import Literal, get_args, override

from langchain_core._api import beta_decorator
from langchain_core.load.dump import dumpd
Expand Down Expand Up @@ -253,7 +253,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."""
for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
type_args = get_args(cls)
Expand All @@ -266,7 +266,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."""
for cls in self.__class__.__orig_bases__: # type: ignore[attr-defined]
type_args = get_args(cls)
Expand Down Expand Up @@ -2669,11 +2669,13 @@ class Config:
arbitrary_types_allowed = True

@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 @@ -3422,6 +3424,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 @@ -3915,6 +3918,7 @@ def __init__(
pass

@property
@override
def InputType(self) -> Any:
func = getattr(self, "_transform", None) or getattr(self, "_atransform")
try:
Expand All @@ -3928,6 +3932,7 @@ def InputType(self) -> Any:
return Any

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

@property
@override
def InputType(self) -> Any:
"""The type of the input to this Runnable."""
func = getattr(self, "func", None) or getattr(self, "afunc")
Expand Down Expand Up @@ -4207,6 +4213,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 @@ -4734,6 +4741,7 @@ class Config:
arbitrary_types_allowed = True

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

Expand All @@ -4749,6 +4757,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 @@ -5036,6 +5045,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 @@ -5044,6 +5054,7 @@ def InputType(self) -> Type[Input]:
)

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

from typing_extensions import override

from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables.base import Runnable, RunnableSerializable
from langchain_core.runnables.config import (
Expand Down Expand Up @@ -71,10 +73,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
4 changes: 4 additions & 0 deletions libs/core/langchain_core/runnables/fallbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
cast,
)

from typing_extensions import override

from langchain_core.load.dump import dumpd
from langchain_core.pydantic_v1 import BaseModel
from langchain_core.runnables.base import Runnable, RunnableSerializable
Expand Down Expand Up @@ -111,10 +113,12 @@ class Config:
arbitrary_types_allowed = True

@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 294d98c

Please sign in to comment.