小编Tom*_*auz的帖子

是否有类似于使用上下文管理器的 Pythonic 方式在后台运行异步任务?

最近想在后台运行一些异步任务,同时运行其他任务,但我认为代码不够Pythonic

task = asyncio.create_task(long_task())
await short_task()
await task
Run Code Online (Sandbox Code Playgroud)

所以我让它更Pythonic

@asynccontextmanager
async def run_in_background(coro):
    task = asyncio.create_task(coro)
    yield task
    await task


async def main():
    async with run_in_background(long_task()):
        await short_task()
Run Code Online (Sandbox Code Playgroud)

像这样的东西已经存在了吗?如果不是,这是否被认为比现有方式更 Pythonic 或更少 Pythonic?

python contextmanager async-await python-asyncio

6
推荐指数
2
解决办法
3993
查看次数

toString 函数或 (std::string) 在 C++ 中强制转换重载

我正在编写一个要转换为字符串的类。

我应该这样做吗:

std::string toString() const;
Run Code Online (Sandbox Code Playgroud)

或者像这样:

operator std::string() const;
Run Code Online (Sandbox Code Playgroud)

什么样的方式更受欢迎?

c++ oop c++11 c++14

4
推荐指数
1
解决办法
2041
查看次数

标签 统计

async-await ×1

c++ ×1

c++11 ×1

c++14 ×1

contextmanager ×1

oop ×1

python ×1

python-asyncio ×1