在尝试回复我自己的question (不管是不是部分的)之后,还有一些东西对我来说仍然是未知的。考虑以下场景:
import asyncio
async def first(f):
async def wrapped():
await asyncio.sleep(0.3) # Something time-consuming
print(f) # <coroutine object second at 0x7fd39f4ff150>
await f
await wrapped()
async def second(f):
async def wrapped():
await asyncio.sleep(0.3) # Something time-consuming
print(f) # <function main at 0x7fd39fe7d7b8>
await f()
await wrapped()
@first
@second
async def main():
print('done')
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main)从first(f)和second(f)中的wrapped()协程中的print(f)中可以看到,first()将second()作为协程对象,而second()将main()作为function()。为什么会这样呢?为什么second()不把main作为一个协程呢?
发布于 2017-03-16 22:15:27
感谢kennytm的评论,
@first
@second
def main():
print('Done')等同于
def main():
pass
main = first(second(main))实际上,@g @f def foo()转换为foo=g(f(foo)。因此,离函数最近的装饰器接受函数本身。
https://stackoverflow.com/questions/42782115
复制相似问题