最近想在后台运行一些异步任务,同时运行其他任务,但我认为代码不够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?
我正在编写一个要转换为字符串的类。
我应该这样做吗:
std::string toString() const;
Run Code Online (Sandbox Code Playgroud)
或者像这样:
operator std::string() const;
Run Code Online (Sandbox Code Playgroud)
什么样的方式更受欢迎?