简体   繁体   English

检测协程是否需要异步循环

[英]Detect if a coroutine needs the asyncio loop

I'm writing code that will wait on user-supplied coroutines using Twisted. 我正在编写将使用Twisted等待用户提供的协程的代码。 In a simpler case all I need is to use defer.ensureDeferred to turn a coroutine into a Deferred. 在更简单的情况下,我需要使用defer.ensureDeferred将协程变成Deferred。 But if a coroutine uses eg asyncio.sleep() I need to use asyncio.ensure_future to wrap it into an asyncio Task that will run in the asyncio loop and this needs AsyncioSelectorReactor . 但是,如果协程使用例如asyncio.sleep() ,则需要使用asyncio.ensure_future将其包装到将在asyncio循环中运行的asyncio任务中,这需要AsyncioSelectorReactor I want to support the first case even if AsyncioSelectorReactor is not used and so I don't want to call asyncio.ensure_future on all coroutines. 即使不使用AsyncioSelectorReactor我也要支持第一种情况,所以我不想在所有协程上调用asyncio.ensure_future The only way to do this that I can think of is somehow detecting if the coroutine needs asyncio, is that possible to do? 我能想到的唯一方法是以某种方式检测协程是否需要异步,这可能吗? Or, maybe, there is a simpler way to do this? 或者,也许有更简单的方法可以做到这一点?

It might help to check if asyncio is referenced inside the coroutine. 检查协程内部是否引用了异步可能会有所帮助。 Consider these examples: 考虑以下示例:

import asyncio

async def test1():
    pass

async def test2():
    await asyncio.sleep(10)

del asyncio
async def test3():
    import asyncio

Using inspect.getclosurevars , you can check for the presence of asyncio: 使用inspect.getclosurevars ,您可以检查asyncio的存在:

assert 'asyncio' not in inspect.getclosurevars(test1).globals or inspect.getclosurevars(test2).globals

assert 'asyncio' in inspect.getclosurevars(test2).globals

assert 'asyncio' in inspect.getclosurevars(test3).unbound

Of course, this is would give a false positive when the user's coroutine imports something from asyncio that doesn't use the loop, such as exceptions or constants, or when the user code doesn't use the imported coroutines. 当然,当用户的协程从asyncio导入不使用循环的某些内容(例如异常或常量),或者用户代码不使用导入的协程时,这将产生误报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM