?1
2345
67def
retry_if_io_error(exception):
return
isinstance
(exception, ioerror)
@retry
(retry_on_exception
=
retry_if_io_error)
def
read_a_file():
with
open
(
"file"
,
"r"
) as f:
return
f.read()
在執行read_a_file
函式的過程中,如果報出異常,那麼這個異常會以形參exception
傳入retry_if_io_error
函式中,如果exception
是ioerror
那麼就進行retry
,如果不是就停止執行並丟擲異常。
我們還可以指定要在得到哪些結果的時候去retry
,這個要用retry_on_result
傳入一個函式物件:?1
2345
6def
retry_if_result_none(result):
return
result
is
none
@retry
(retry_on_result
=
retry_if_result_none)
def
get_result():
return
none
在執行get_result
成功後,會將函式的返回值通過形參result
的形式傳入retry_if_result_none
函式中,如果返回值是none
那麼就進行retry
,否則就結束並返回函式值。
總結