简体   繁体   English

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

[英]Python: Pass execution statement as function parameter

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

In the code above, how can I wrap this whole thing up as a function and make it so that any command (in this example, 'graph.put_event(**args)') can be passed in as a parameter to be executed within the function? 在上面的代码中,我如何将整个事物作为一个函数包装起来并使其成为任何命令(在此示例中,'graph.put_event(** args)')可以作为要在其中执行的参数传入功能?

To directly answer your question: 直接回答你的问题:

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

This can then be called as such: 然后可以这样调用:

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

As an aside, given the above task, I would write it along the lines of: 顺便说一下,鉴于上述任务,我会按照以下方式编写:

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
def do_event(evt, *args, **kwargs):
   ...
      retVal = evt(*args, **kwargs)
   ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM