民间, 在必要时,python 不执行语句的正确方法是什么。
假设我有一个指数api退避函数:
def exponential_backoff_task(config, task, description):
retry_count = config.get( 'retry_count', 5 )
api_backoff_initial_msec = config.get( 'api_backoff_initial_msec', 200)
print 'Running api-backoff task: %s, retry_count: %d, initial_backoff: %d' % (description, retry_count, api_backoff_initial_msec)
result = None
for r in range(retry_count):
try:
result = task
except boto.exception.BotoServerError:
delay_msec = (2 ** r) * api_backoff_initial_msec
print 'Exponential backoff, retry %d for %d msecs...' % (r, delay_msec)
time.sleep(delay_msec/1000)
continue
except:
raise
return result
def foo():
all_instances = exponential_backoff_task(config, conn.get_all_dbinstances(), 'foo'))
在这种情况下,conn.get_all_instances()
在调用函数时执行,而不是在exponential_backup
函数内部执行
谢谢!
答案 0 :(得分:2)
传入时不要调用它,只在需要时调用它:
from functools import partial
def exponential_backoff_task(config, task_fn, description):
retry_count = config.get('retry_count', 5)
api_backoff_initial_msec = config.get('api_backoff_initial_msec', 200)
print 'Running api-backoff task: %s, retry_count: %d, initial_backoff: %d' % (description, retry_count, api_backoff_initial_msec)
result = None
for r in range(retry_count):
try:
# Call the function that got passed in
result = task_fn()
except boto.exception.BotoServerError:
delay_msec = (2 ** r) * api_backoff_initial_msec
print 'Exponential backoff, retry %d for %d msecs...' % (r, delay_msec)
time.sleep(delay_msec / 1000)
continue
except:
raise
return result
def foo():
# Note the missing parens: here you're just passing in the function
all_instances = exponential_backoff_task(config, conn.get_all_dbinstances, 'foo')
修改强>:
要在函数中预定义一些参数,你可以使用partial
,它可以接受一个函数将参数应用于它并返回一个已经应用了这些参数的新函数,这是一个例子:
from functools import partial
def f(a, b):
print a
print b
g = partial(f, a=1, b=2)
g()
打印
1
2