如何从装饰函数中获取装饰器访问变量?

时间:2017-10-11 13:48:15

标签: python timeout signals decorator python-decorators

我正在使用通用的Python超时装饰器。我希望decorater从它正在装饰的函数中访问变量。在这个例子中,我希望消息从prepare函数传递到timeout函数。我不想使用全局变量,因为这听起来像是不好的做法。

def timeout(seconds):
    def decorator(func):
        def _handle_timeout(signum, frame):
            # Do something with variable message
            print("Sending the message didn't work!")
            print(message)
        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

@timeout(5)
def prepare(message):
    """Deploy app using Heroku to the MTurk Sandbox."""
    print("Preparing to send message!")
    send(message)

1 个答案:

答案 0 :(得分:1)

将处理程序推送到包装器中,以便它可以访问该变量。

from functools import wraps
import signal
import time

def timeout(seconds):
    def decorator(func):
        def wrapper(message, *args, **kwargs):
            def _handle_timeout(signum, frame):
                # Do something with variable message
                print("Sending the message didn't work!")
                print(message)
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(message, *args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

@timeout(1)
def prepare(message):
    # Uncomment to force error
    # time.sleep(3)
    """Deploy app using Heroku to the MTurk Sandbox."""
    print("Preparing to send message!")
    print(message)


if __name__ == "__main__":
    prepare("hi")