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

Python:将执行语句作为函数参数传递,python,Python,在上面的代码中,我如何将整个过程包装为一个函数,并使其能够将任何命令(在本例中为“graph.put_event(**args)”)作为参数传入函数中执行?直接回答您的问题: retVal = None retries = 5 success = False while retries > 0 and success == False: try: retVal = graph.put_event(**args) success = True

在上面的代码中,我如何将整个过程包装为一个函数,并使其能够将任何命令(在本例中为“graph.put_event(**args)”)作为参数传入函数中执行?

直接回答您的问题:

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
def do_event(evt, *args, **kwargs):
   ...
      retVal = evt(*args, **kwargs)
   ...
这可以被称为:

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