gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:22 26 4
gpt4 key购买 nike

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

最佳答案

直接回答您的问题:

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

关于Python:将执行语句作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6371041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com