2011-06-16 46 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) 
    ...