Answer the question
In order to leave comments, you need to log in
Is it possible to make a decorator that works with both asynchronous and synchronous functions?
Let's say we just have a decorator:
def if_no_data(f):
def wrapper(self, *args, **kwargs):
if not self.data:
return f(self, *args, **kwargs)
return wrapper
def if_no_data(f):
async def wrapper(self, *args, **kwargs):
if not self.data:
result = f(self, *args, **kwargs)
try:
return await result
except ValueError:
return result
return wrapper
Answer the question
In order to leave comments, you need to log in
Something like that
def if_no_data(f):
async def wrapper(self, *args, **kwargs):
if self.data:
return None
if asyncio.iscoroutinefunction(f):
return await f(self, *args, **kwargs)
else:
return f(self, *args, **kwargs)
return wrapper
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question