2011-06-16 43 views
2
retVal = None 
retries = 5 
success = False 
while retries > 0 and success == False: 
    try: 
     retVal = graph.put_event(**args) 
     success = True 
    except: 
     retries = retries-1 
     logging.info('Facebook put_event timed out. Retrying.') 
return success, retVal 

在上面的代碼,我該怎麼包裝這整個事情了作爲一個功能,讓這個任何命令(在這個例子中,「graph.put_event(** ARGS )')可以作爲參數傳入以在函數內執行?的Python:通過執行語句,函數參數

回答

3

直接回答你的問題:

def foo(func, *args, **kwargs): 
    retVal = None 
    retries = 5 
    success = False 
    while retries > 0 and success == False: 
     try: 
      retVal = func(*args, **kwargs) 
      success = True 
     except: 
      retries = retries-1 
      logging.info('Facebook put_event timed out. Retrying.') 
    return success, retVal 

這可以被稱爲例如:

s, r = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world") 

順便說一句,給出了上述的任務,我會寫沿一行:

class CustomException(Exception): pass 

# Note: untested code... 
def foo(func, *args, **kwargs): 
    retries = 5 
    while retries > 0: 
     try: 
      return func(*args, **kwargs) 
     except: 
      retries -= 1 
      # maybe sleep a short while 
    raise CustomException 

# to be used as such 
try: 
    rv = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world") 
except CustomException: 
    # handle failure 
3
def do_event(evt, *args, **kwargs): 
    ... 
     retVal = evt(*args, **kwargs) 
    ...