[英]How to pass argument to decorator dynamically based on certain condition in python?
我已經用名為--- timeout.py的文件編寫了一個超時裝飾器函數。
from functools import wraps
import errno
import os
import signal
class TimeoutError(Exception):
pass
def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
def decorator(func):
def _handle_timeout(signum, frame):
raise TimeoutError(error_message)
@wraps(func)
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 wrapper
return decorator
現在我有另一個文件,在另一個文件中具有以下代碼
"""some code at the starting"""
if keyword == 'this_one':
real_time_reading(this_one) #how to send timeout_in_seconds dynamically
elif keyword == 'that_one':
real_time_reading(this_one)
@timeout(timeout_in_seconds)
def real_time_reading(keyword):
'''Here it does some operations and if there is no input
it times out based on the timeout_in_seconds value given
to decorator'''
我的要求基於要發送timeout_in_seconds到decorator的關鍵字。
意思是,如果keyword =='this_one',則real_time_reading函數應在30秒后超時;如果keyword =='that_one',則real_time_reading函數應在60秒后超時。
有沒有一種方法可以根據特定條件動態發送裝飾器參數?
不,在解析函數時會初始化裝飾器。 可能存在動態更改(修改)它的方法,但這會產生不良后果。
我建議使用兩個功能:
"""some code at the starting"""
if keyword == 'this_one':
real_time_reading_this_one(keyword)
elif keyword == 'that_one':
real_time_reading_that_one(keyword)
@timeout(timeout_in_seconds)
def real_time_reading_this_one(keyword)
return _real_time_reading(keyword);
@timeout(timeout_in_seconds * 2)
def real_time_reading_that_one(keyword)
return _real_time_reading(keyword);
def _real_time_reading(keyword):
'''Here it does some operations and if there is no input
it times out based on the timeout_in_seconds value given
to decorator'''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.