mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-11 00:58:30 +00:00
chore: refactor and type memoize utility function
This commit is contained in:
@@ -1,14 +1,38 @@
|
|||||||
|
"""Utility functions for the crewai project module."""
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
from typing import Any, ParamSpec, TypeVar
|
||||||
|
|
||||||
|
P = ParamSpec("P")
|
||||||
|
R = TypeVar("R")
|
||||||
|
|
||||||
|
|
||||||
def memoize(func):
|
def memoize(meth: Callable[P, R]) -> Callable[P, R]:
|
||||||
cache = {}
|
"""Memoize a method by caching its results based on arguments.
|
||||||
|
|
||||||
@wraps(func)
|
Args:
|
||||||
def memoized_func(*args, **kwargs):
|
meth: The method to memoize.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A memoized version of the method that caches results.
|
||||||
|
"""
|
||||||
|
cache: dict[Any, R] = {}
|
||||||
|
|
||||||
|
@wraps(meth)
|
||||||
|
def memoized_func(*args: P.args, **kwargs: P.kwargs) -> R:
|
||||||
|
"""Memoized wrapper method.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
*args: Positional arguments to pass to the method.
|
||||||
|
**kwargs: Keyword arguments to pass to the method.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The cached or computed result of the method.
|
||||||
|
"""
|
||||||
key = (args, tuple(kwargs.items()))
|
key = (args, tuple(kwargs.items()))
|
||||||
if key not in cache:
|
if key not in cache:
|
||||||
cache[key] = func(*args, **kwargs)
|
cache[key] = meth(*args, **kwargs)
|
||||||
return cache[key]
|
return cache[key]
|
||||||
|
|
||||||
return memoized_func
|
return memoized_func
|
||||||
|
|||||||
Reference in New Issue
Block a user