Proteusiq / hadithi

🧪 Data Science | ⚒️ MLOps | ⚙️ DataOps : Talks about 🦄
15 stars 1 forks source link

awesome decorators #59

Open Proteusiq opened 2 weeks ago

Proteusiq commented 2 weeks ago
from functools import wraps

def run_until(condition, max_attempts=None):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            if condition(result):
                return result

            if max_attempts is not None and wrapper.attempts == max_attempts:
                raise Exception("Max attempts reached without meeting the condition")

            wrapper.attempts += 1
            return wrapper(*args, **kwargs)

        wrapper.attempts = 0
        return wrapper

    return decorator
import time

class cacher:
    """helper function to return cached response within certain period"""

    def __init__(self, timeout):
        self.timeout = timeout
        self.cache = {}

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            wrapper.__name__ = func.__name__
            wrapper.__doc__ = func.__doc__

            current_time = time.time()
            if "last_called" in self.cache:
                elapsed_time = current_time - self.cache["last_called"]
                if elapsed_time < self.timeout:
                    return self.cache["result"]
            result = func(*args, **kwargs)
            self.cache["last_called"] = current_time
            self.cache["result"] = result
            return result

        return wrapper