Commit 5f412905 authored by BO ZHANG's avatar BO ZHANG 🏀
Browse files

add retry

parent fc788084
Loading
Loading
Loading
Loading
+4 −0
Original line number Diff line number Diff line
@@ -10,4 +10,8 @@ Modified-History:
"""

from ._module_docstr import ModuleHeader
from ._retry import retry
from .tempfile import randfile


+29 −0
Original line number Diff line number Diff line
"""
Identifier:     csst_common/utils/_retry.py
Name:           _retry.py
Description:    CSST utils
Author:         Bo Zhang
Created:        2023-12-20
Modified-History:
    2023-12-20, Bo Zhang, add retry
"""


def retry(func, n_try=3, *args, **kwargs):
    # is DFS?
    try:
        assert func.__self__.__class__.__module__.startswith("csst_dfs_api"), func
        is_dfs = True
    except BaseException:
        is_dfs = False
    # start trials
    for attempt in range(n_try):
        print(f"Trial #{attempt}: call {func}")
        try:
            res = func(*args, **kwargs)
            if is_dfs:
                assert res["code"] == 0, res
            return res
        except BaseException as e:
            print(f"Error occurs: {e.__repr__()}")
    raise RuntimeError(f"All {n_try} attempts failed.")