Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

awesome decorators #59

Open
Proteusiq opened this issue Jun 29, 2024 · 0 comments
Open

awesome decorators #59

Proteusiq opened this issue Jun 29, 2024 · 0 comments

Comments

@Proteusiq
Copy link
Owner

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant