python-notebooks-async

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Notebooks Async

Python 笔记本异步编程

Overview

概述

Notebook kernels own the event loop; async code must cooperate with that ownership rather than fight it. This skill covers orchestration patterns, top-level
await
, and compatibility constraints for
.ipynb
and
#%%
workflows.
Treat these recommendations as preferred defaults. When project constraints require deviation, call out tradeoffs and compensating controls.
笔记本内核拥有事件循环的所有权;异步代码必须配合这种所有权机制,而非与之对抗。本技能涵盖了.ipynb和#%%工作流的编排模式、顶层await使用方法,以及兼容性约束。
将这些建议视为首选默认方案。当项目约束要求偏离默认方案时,需明确说明权衡取舍和补偿控制措施。

When to Use

适用场景

  • asyncio.run()
    raises
    RuntimeError
    inside a notebook cell.
  • Event-loop conflicts when mixing async libraries in Jupyter.
  • Porting async scripts into notebook workflows.
  • Orchestrating concurrent tasks (
    gather
    ,
    TaskGroup
    ) in IPython kernels.
  • Deciding where to place reusable async logic across notebook/module boundaries.
  • 在笔记本单元格中调用asyncio.run()时触发RuntimeError。
  • 在Jupyter中混合使用异步库时出现事件循环冲突。
  • 将异步脚本移植到笔记本工作流中。
  • 在IPython内核中编排并发任务(gather、TaskGroup)。
  • 决定在笔记本/模块边界之间放置可复用异步逻辑的位置。

When NOT to Use

不适用场景

  • Pure script or service code with no notebook involvement — see
    python-concurrency-performance
    .
  • Synchronous notebook workflows with no async needs.
  • General asyncio API design outside notebook contexts — see
    python-runtime-operations
    .
  • 不涉及笔记本的纯脚本或服务端代码——请参考
    python-concurrency-performance
  • 无异步需求的同步笔记本工作流。
  • 笔记本上下文之外的通用asyncio API设计——请参考
    python-runtime-operations

Quick Reference

快速参考

  • Treat notebook kernels as loop-owned environments; never create a competing loop.
  • Use top-level
    await
    instead of
    asyncio.run()
    in notebook cells.
  • Orchestrate concurrent work with
    asyncio.gather()
    or
    asyncio.TaskGroup
    .
  • Keep reusable async logic in regular
    .py
    modules, imported into notebooks.
  • Use
    nest_asyncio
    only as a constrained compatibility fallback, not a default.
  • Avoid fire-and-forget tasks — always
    await
    or collect results explicitly.
  • 将笔记本内核视为拥有事件循环的环境;绝不要创建竞争性的事件循环。
  • 在笔记本单元格中使用顶层await替代asyncio.run()。
  • 使用asyncio.gather()或asyncio.TaskGroup编排并发工作。
  • 将可复用的异步逻辑保存在常规的.py模块中,再导入到笔记本中。
  • 仅将nest_asyncio作为受限的兼容性回退方案,而非默认选择。
  • 避免“触发即遗忘”的任务——始终显式await或收集结果。

Common Mistakes

常见错误

  • Calling
    asyncio.run()
    in a notebook cell.
    The kernel already runs a loop;
    asyncio.run()
    tries to start a second one and raises
    RuntimeError
    . Use
    await
    directly instead.
  • Applying
    nest_asyncio
    globally by default.
    It patches the loop to allow reentrant calls but masks design problems and can hide subtle concurrency bugs. Reserve it for legacy compatibility.
  • Defining async helpers inline in cells instead of modules. Inline definitions are lost on kernel restart and cannot be tested outside the notebook. Extract to
    .py
    files.
  • Ignoring returned tasks or coroutines. Calling an async function without
    await
    silently produces a never-executed coroutine object, with no error until results are missing downstream.
  • Mixing blocking I/O with async in the same cell. Synchronous calls like
    requests.get()
    block the event loop, starving concurrent tasks. Use
    aiohttp
    ,
    httpx
    , or
    asyncio.to_thread()
    .
  • 在笔记本单元格中调用asyncio.run() 内核已在运行一个事件循环;asyncio.run()尝试启动第二个事件循环,从而触发RuntimeError。 请直接使用await替代。
  • 默认全局应用nest_asyncio 它会对事件循环打补丁以允许重入调用,但会掩盖设计问题,还可能隐藏微妙的并发bug。 仅将其用于遗留代码兼容场景。
  • 在单元格中内联定义异步辅助函数而非模块中 内联定义的内容在内核重启后会丢失,且无法在笔记本外进行测试。 请将其提取到.py文件中。
  • 忽略返回的任务或协程 调用异步函数却不使用await会静默生成一个从未执行的协程对象,直到下游缺少结果时才会出现错误。
  • 在同一单元格中混合阻塞I/O与异步代码 像requests.get()这样的同步调用会阻塞事件循环,导致并发任务资源不足。 请使用aiohttp、httpx或asyncio.to_thread()替代。

Scope Note

范围说明

  • Treat these recommendations as preferred defaults for common cases, not universal rules.
  • If a default conflicts with project constraints or worsens the outcome, suggest a better-fit alternative and explain why it is better for this case.
  • When deviating, call out tradeoffs and compensating controls (tests, observability, migration, rollback).
  • 将这些建议视为常见场景下的首选默认方案,而非通用规则。
  • 如果默认方案与项目约束冲突或导致结果恶化,请提出更合适的替代方案,并解释为何该方案更适合当前场景。
  • 当偏离默认方案时,需明确说明权衡取舍和补偿控制措施(测试、可观测性、迁移、回滚)。

Invocation Notice

调用说明

  • Inform the user when this skill is being invoked by name:
    python-design-modularity
    .
  • 当调用本技能时,需告知用户技能名称:
    python-design-modularity

References

参考资料

  • references/notebooks-async.md
  • references/notebooks-async.md