python [Python Async Decorator] #python #asyncio #decorator

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python [Python Async Decorator] #python #asyncio #decorator相关的知识,希望对你有一定的参考价值。

import asyncio

from functools import wraps


def dec(fn):
    @wraps(fn)
    async def wrapper(*args, **kwargs):
        print(fn, args, kwargs)  # <function foo at 0x10952d598> () {}
        await asyncio.sleep(5)
        print("done with wrapper, going to call fn")
        return await fn()
    return wrapper
    
@dec
async def foo():
    return await asyncio.sleep(5, result="i'm done")
    
loop = asyncio.get_event_loop()
result = loop.run_until_complete(foo())  

print(result)  # i'm done

loop.close()
import asyncio
import time

from functools import wraps


def dec(fn):
    if asyncio.iscoroutinefunction(fn):
        @wraps(fn)
        async def wrapper(*args, **kwargs):
            print(fn, args, kwargs)  # <function foo at 0x10952d598> () {}
            await asyncio.sleep(5)
            print("done with wrapper, going to call fn")
            return await fn()
        return wrapper
    else:
        @wraps(fn)
        def wrapper(*args, **kwargs):
            print(fn, args, kwargs)  # <function bar at 0x108fb5a60> () {}
            time.sleep(5)
            print("done with wrapper, going to call fn")
            return fn()
        return wrapper
    
@dec
async def foo():
    return await asyncio.sleep(5, result="async function done")
  
@dec
def bar():
    time.sleep(5)
    return "sync function done"
    
loop = asyncio.get_event_loop()
result = loop.run_until_complete(foo())  

print(result)  # async function done
print(bar())   # sync  function done

loop.close()
import asyncio

from functools import wraps


async def foo():
    return await asyncio.sleep(5, result="i'm done")
    
loop = asyncio.get_event_loop()
result = loop.run_until_complete(foo())

print(result)  # i'm done

loop.close()

以上是关于python [Python Async Decorator] #python #asyncio #decorator的主要内容,如果未能解决你的问题,请参考以下文章

python deco args测试

python 装饰器

Python全栈day28(类的装饰器)

python装饰器(备忘)

Python函数调用的问题

python装饰器系列