简体   繁体   中英

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?

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)
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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