Python 如何让装饰器从装饰函数中访问变量?
我正在使用一个通用的Python超时装饰程序。我希望装饰程序从它正在装饰的函数中访问变量。在本例中,我希望消息从prepare函数传递到timeout函数。我不想使用全局变量,因为这听起来像是坏习惯Python 如何让装饰器从装饰函数中访问变量?,python,timeout,signals,decorator,python-decorators,Python,Timeout,Signals,Decorator,Python Decorators,我正在使用一个通用的Python超时装饰程序。我希望装饰程序从它正在装饰的函数中访问变量。在本例中,我希望消息从prepare函数传递到timeout函数。我不想使用全局变量,因为这听起来像是坏习惯 def timeout(seconds): def decorator(func): def _handle_timeout(signum, frame): # Do something with variable message
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)
将处理程序推入包装器,使其能够访问该变量
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")
它已经可以访问参数,您认为
args
中有什么?我收到一个错误,变量不存在。。我似乎无法将变量传递到_handle_timeout函数中。该函数在包装器
之外,因此它无法访问这些参数。请注意,您应该给出一个包含特定错误回溯的示例。明白了,我将编辑我的示例。所以我假设我需要修复_handle_timeout,以便它可以接受包装器中的变量?我将对此进行测试,并提供更多细节。jonrsharpe,martineau:问题实际上并不在于包装器是否能够到达消息(尽管在我下面的回答中,我明确指出了这一点),而是signal.signal方法不接受任意参数。