Python:将执行语句作为函数参数传递

时间:2011-06-16 11:26:49

标签: python

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)')可以作为参数传递给在函数内执行?

2 个答案:

答案 0 :(得分:3)

def do_event(evt, *args, **kwargs):
   ...
      retVal = evt(*args, **kwargs)
   ...

答案 1 :(得分: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