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

Sha*_*ram 3 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
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我如何将整个事情包装为一个函数,并使任何命令(在本例中为“graph.put_event(**args)”)都可以作为要在其中执行的参数传递功能?

Sha*_*hin 5

直接回答你的问题:

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
Run Code Online (Sandbox Code Playgroud)

然后可以这样调用:

s, r = foo(graph.put_event, arg1, arg2, kwarg1="hello", kwarg2="world")
Run Code Online (Sandbox Code Playgroud)

顺便说一句,鉴于上述任务,我会按照以下方式编写:

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
Run Code Online (Sandbox Code Playgroud)