hello everyone.
This is sync three-layer nested python decorator.
from typing import Callable
def condition_retry(condition: Callable) -> Callable:
count = 0
def outer(func: Callable):
def wrapper(*args, **kwargs):
nonlocal count
if count > 0:
print(f"{func.__name__} start.")
rt = func(*args, **kwargs)
if condition(rt):
count += 1
print(f"{func.__name__} retry {count} times.")
return wrapper(*args, **kwargs)
count = 0
return rt
return wrapper
return outer
@condition_retry(lambda x: x!="a")
def func(a):
print(a)
return a
func("a")
How to define an asynchronous decorator with the same version?
This is a final result. successful!
import asyncio
from typing import Callable
def condition_retry(condition: Callable) -> Callable:
count = 0
def outer(func: Callable):
async def wrapper(*args, **kwargs):
nonlocal count
if count > 0:
print(f"{func.__name__} start.")
rt = await func(*args, **kwargs)
if condition(rt):
count += 1
print(f"{func.__name__} retry {count} times.")
return await wrapper(*args, **kwargs)
count = 0
return rt
return wrapper
return outer
@condition_retry(lambda x: x!="a")
async def func(a):
print(a)
return a
asyncio.run(func("a"))