[英]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
在上面的代碼中,我如何將整個事物作為一個函數包裝起來並使其成為任何命令(在此示例中,'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
def do_event(evt, *args, **kwargs):
...
retVal = evt(*args, **kwargs)
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.