简体   繁体   English

python函数参数执行

[英]python function parameter execution

Folks, What is the proper way in python not to execute a statement until necessary. 伙计们,什么是蟒蛇执行语句,直到必要的正确方法。

Lets say I have a function that does exponential api backoff: 可以说我有一个执行指数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'))

In this case, conn.get_all_instances() gets executed when a function is called, instead of being exercised inside the exponential_backup function 在这种情况下, conn.get_all_instances()在调用函数时执行,而不是在exponential_backup函数内部执行

Thanks! 谢谢!

Well don't call it when passing it in, and only call it when you need it: 好吧,不要在传入时调用它,而仅在需要时才调用它:

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')

EDIT : To predefine some arguments in your function you can use partial , that can take in a function apply the arguments to it and return a new function with those arguments already applied, here's an example: 编辑 :要在函数中预定义一些参数,可以使用partial ,可以接受函数将参数应用到该函数,然后使用已应用的那些参数返回一个新函数,这是一个示例:

from functools import partial

def f(a, b):
    print a
    print b

g = partial(f, a=1, b=2)

g()

This prints 此打印

1
2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM