Skip to content

Commit

Permalink
core: Cache RunnableLambda __repr__ (#29199)
Browse files Browse the repository at this point in the history
`RunnableLambda`'s `__repr__` may do costly OS operation by calling
`get_lambda_source`.
So it's better to cache it.
See #29043

---------

Co-authored-by: Chester Curme <[email protected]>
  • Loading branch information
cbornet and ccurme authored Jan 23, 2025
1 parent 618e550 commit b6ae7ca
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions libs/core/langchain_core/runnables/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4347,6 +4347,8 @@ def __init__(
except AttributeError:
pass

self._repr: Optional[str] = None

@property
@override
def InputType(self) -> Any:
Expand Down Expand Up @@ -4525,14 +4527,18 @@ def __eq__(self, other: Any) -> bool:

def __repr__(self) -> str:
"""A string representation of this Runnable."""
if hasattr(self, "func") and isinstance(self.func, itemgetter):
return f"RunnableLambda({str(self.func)[len('operator.') :]})"
elif hasattr(self, "func"):
return f"RunnableLambda({get_lambda_source(self.func) or '...'})"
elif hasattr(self, "afunc"):
return f"RunnableLambda(afunc={get_lambda_source(self.afunc) or '...'})"
else:
return "RunnableLambda(...)"
if self._repr is None:
if hasattr(self, "func") and isinstance(self.func, itemgetter):
self._repr = f"RunnableLambda({str(self.func)[len('operator.') :]})"
elif hasattr(self, "func"):
self._repr = f"RunnableLambda({get_lambda_source(self.func) or '...'})"
elif hasattr(self, "afunc"):
self._repr = (
f"RunnableLambda(afunc={get_lambda_source(self.afunc) or '...'})"
)
else:
self._repr = "RunnableLambda(...)"
return self._repr

def _invoke(
self,
Expand Down

0 comments on commit b6ae7ca

Please sign in to comment.