2016-03-29 6 views
0

フォーク、 は適切な方法で、は必要になるまで文を実行できません。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

あなたのメソッド内で 'task()'を呼び出すことは決してありません。単に 'all_instances'に' None'を返すだけです。 –

答えて

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

EDIT: あなたがpartialを使用することができますあなたの関数ではいくつかの引数を事前定義するには、その缶それに引数を適用し、すでに適用され、それらの引数を持つ新しい関数を返す関数の中で取る、ここに例を示します

from functools import partial 

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

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

g() 

これは

0123を印刷します
+0

'conn.get_all_dbinstances'を特定のパラメータでインスタンス化したいのですが? – Cmag

+0

@Cmag編集済みの回答を表示 – Bahrom

関連する問題