我有以下的超時創作裝飾功能:如何編寫可以獲取函數或裝飾函數的超時裝飾器?
class TimeoutError(Exception): pass
def timeout(seconds, error_message = 'Function call timed out'):
def decorated(func):
print "timeout: \t" + func.__name__
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
def wrapper(*args, **kwargs):
signal.signal(signal.SIGALRM, _handle_timeout)
signal.alarm(seconds)
try:
print "timeout wrapper: \t" + func.__name__
result = func(*args, **kwargs)
finally:
signal.alarm(0)
return result
return functools.wraps(func)(wrapper)
return decorated
而另一家裝飾:
import inspect
class withHostAndToken(object):
__name__ = "withHostAndToken"
__doc__ = "Get the Host and Token for the API call"
def __init__(self, func):
print "withHostAndToken: \t" + func.__name__
self.func = func
self.HOST = ''
self.TOKEN = ''
def __call__(self,*args, **kwds):
if self.HOST == '':
self.HOST = "HOST"
if self.TOKEN == '':
self.TOKEN = "TOKEN"
argsspec = inspect.getargspec(self.func)
function_args = argsspec[0]
if 'HOST' in function_args:
if 'TOKEN' in function_args:
return self.func(self.HOST , self.TOKEN , *args, **kwds)
else:
return self.func(self.HOST , *args, **kwds)
elif 'TOKEN' in function_args:
return self.func(self.TOKEN, *args, **kwds)
當我嘗試既適用於功能我不;噸得到被調用的函數的代碼:
@timeout(2)
@withHostAndToken
def testDecorators():
print __name__
while True:
print '.'
testDecorators()
的這個輸出是:
withHostAndToken:testDecorators
超時:withHostAndToken
超時包裝:withHostAndToken進程退出代碼爲0完
是不是這裏的問題,你的*內*裝飾類不換行的財產?它應該保留'__name__'和'__doc__';見例如https://docs.python.org/3/library/functools.html#functools.wraps – jonrsharpe
'__name__'和'__doc__'不應該是方法。使它們成爲常規的實例屬性或屬性。 – user2357112