M
M
Max Payne2019-03-29 16:32:12
Python
Max Payne, 2019-03-29 16:32:12

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

The essence of its work is simple - to check the property of the object for emptiness. Great, but what if you want the decorator to work with both asynchronous and synchronous functions?
Something like this looks very strange, and it is unlikely to work.
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

1 answer(s)
A
Alexander Bragin, 2019-03-29
@YardalGedal

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 question

Ask a Question

731 491 924 answers to any question