python-development
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Development Skill
Python开发技能
Reference data for the Developer Hub, Python Specialist, and wxPython Specialist agents.
供开发者中心、Python专家Agent和wxPython专家Agent使用的参考数据。
Python Version Quick Reference
Python版本快速参考
| Version | Key Features | EOL |
|---|---|---|
| 3.10 | | Oct 2026 |
| 3.11 | Exception groups, | Oct 2027 |
| 3.12 | Type parameter syntax | Oct 2028 |
| 3.13 | Experimental free-threaded mode, improved error messages | Oct 2029 |
| 3.14 | | Oct 2030 |
| 版本 | 核心特性 | 停止支持时间 |
|---|---|---|
| 3.10 | | 2026年10月 |
| 3.11 | 异常组、 | 2027年10月 |
| 3.12 | 类型参数语法 | 2028年10月 |
| 3.13 | 实验性无全局解释器锁模式、优化的错误提示 | 2029年10月 |
| 3.14 | | 2030年10月 |
pyproject.toml Skeleton
pyproject.toml 基础模板
toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "my-app"
version = "1.0.0"
requires-python = ">=3.10"
dependencies = []
[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.6", "mypy>=1.11"]
[project.scripts]
myapp = "my_app.__main__:main"
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
[tool.ruff]
target-version = "py310"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "SIM", "TCH"]
[tool.mypy]
python_version = "3.10"
strict = truetoml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "my-app"
version = "1.0.0"
requires-python = ">=3.10"
dependencies = []
[project.optional-dependencies]
dev = ["pytest>=8.0", "ruff>=0.6", "mypy>=1.11"]
[project.scripts]
myapp = "my_app.__main__:main"
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
[tool.ruff]
target-version = "py310"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "SIM", "TCH"]
[tool.mypy]
python_version = "3.10"
strict = truePyInstaller Quick Reference
PyInstaller 快速参考
One-File Mode
单文件模式
python
exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas,
name='MyApp', console=False, icon='icon.ico')python
exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas,
name='MyApp', console=False, icon='icon.ico')One-Folder Mode
单文件夹模式
python
exe = EXE(pyz, a.scripts, exclude_binaries=True,
name='MyApp', console=False, icon='icon.ico')
coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='MyApp')python
exe = EXE(pyz, a.scripts, exclude_binaries=True,
name='MyApp', console=False, icon='icon.ico')
coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='MyApp')Common Hidden Imports
常见隐式导入
pkg_resources.extern- (for a11y desktop apps)
accessible_output2 - (for credential storage)
keyring.backends platformdirs- /
httpx._transportshttpcore._backends - (always needed)
encodings
pkg_resources.extern- (无障碍桌面应用使用)
accessible_output2 - (凭证存储使用)
keyring.backends platformdirs- /
httpx._transportshttpcore._backends - (始终需要导入)
encodings
wxPython Quick Reference
wxPython 快速参考
Sizer Cheat Sheet
Sizer速查表
| Sizer | When to Use |
|---|---|
| Stack items top-to-bottom |
| Lay items left-to-right |
| Form layouts with labels + controls |
| Even grid layouts |
| Flow layout that wraps |
| Grouped controls with border |
| Sizer | 使用场景 |
|---|---|
| 从上到下堆叠元素 |
| 从左到右排列元素 |
| 带标签+控件的表单布局 |
| 均匀网格布局 |
| 可自动换行的流式布局 |
| 带边框的分组控件 |
Thread-Safe GUI Updates
线程安全的GUI更新
python
undefinedpython
undefinedFrom worker thread:
来自工作线程的调用:
wx.CallAfter(self.update_status, "Done")
wx.PostEvent(self, CustomEvent(data=result))
wx.CallAfter(self.update_status, "Done")
wx.PostEvent(self, CustomEvent(data=result))
NEVER do this from a worker thread:
严禁在工作线程中执行以下操作:
self.status_bar.SetStatusText("Done") # CRASH or CORRUPTION
undefinedself.status_bar.SetStatusText("Done") # 会导致崩溃或数据损坏
undefinedStandard IDs
标准ID
| ID | Purpose |
|---|---|
| OK button |
| Cancel button |
| Save action |
| Open action |
| Exit / Quit |
| Help action |
| New document |
| Undo / Redo |
| ID | 用途 |
|---|---|
| 确认按钮 |
| 取消按钮 |
| 保存操作 |
| 打开操作 |
| 退出操作 |
| 帮助操作 |
| 新建文档 |
| 撤销/重做 |
Event Types
事件类型
| Event | Trigger |
|---|---|
| Button click |
| Menu item selected |
| Window close requested |
| Window resized |
| Timer fired |
| Text control content changed |
| List item selected |
| Tree selection changed |
| UI state update check |
| 事件 | 触发条件 |
|---|---|
| 按钮点击 |
| 菜单项被选中 |
| 收到窗口关闭请求 |
| 窗口大小调整 |
| 计时器触发 |
| 文本控件内容变更 |
| 列表项被选中 |
| 树形控件选中项变更 |
| UI状态更新检查 |
Common Pitfalls
常见陷阱
Python
Python
- Mutable default arguments: shares the list across calls. Use
def f(items=[])and create inside.None - Late binding closures: in a loop captures the variable, not the value. Use
lambda: x.lambda x=x: x - Circular imports: Move imports inside functions, use block, or restructure modules.
TYPE_CHECKING - outside dataclass:
field()is only valid insidefield()classes. Use plain type annotations elsewhere.@dataclass - vs
is:==checks identity,ischecks equality. Use==only foris,None,True.False - String concatenation in loops: Use or
"".join()instead.io.StringIO
- 可变默认参数: 会在多次调用间共享同一个列表,使用
def f(items=[])并在函数内部创建列表。None - 闭包晚绑定: 循环中定义的 会捕获变量本身而非当前值,使用
lambda: x规避。lambda x=x: x - 循环导入: 将导入语句移到函数内部、使用 块或重构模块结构解决。
TYPE_CHECKING - 在数据类外使用:
field()仅在field()装饰的类中有效,其他位置使用普通类型注解即可。@dataclass - 和
is混淆:==检查身份,is检查值相等,仅在判断==、None、True时使用False。is - 循环中字符串拼接: 优先使用 或
"".join()。io.StringIO
wxPython
wxPython
- GUI from worker thread: Always use or
wx.CallAfter().wx.PostEvent() - Missing : Other handlers won't fire. Call
event.Skip()unless you intentionally consume the event.event.Skip() - Timer not stopped: Stop timers in handler to prevent callbacks after destruction.
EVT_CLOSE - AUI not uninitialized: Call in close handler.
_mgr.UnInit() - Dialog not destroyed: Use context managers () for automatic cleanup.
with MyDialog(...) as dlg: - Wrong parent for sizer items: All controls in a sizer must have the same parent panel.
- Absolute positioning: Never use or
SetPosition()for layout. Always use sizers.SetSize()
- 在工作线程操作GUI: 始终使用 或
wx.CallAfter()。wx.PostEvent() - 遗漏: 其他事件处理器不会被触发,除非你有意消费该事件,否则需要调用
event.Skip()。event.Skip() - 未停止计时器: 在 处理器中停止计时器,避免窗口销毁后回调触发异常。
EVT_CLOSE - AUI未初始化销毁: 在关闭处理器中调用 。
_mgr.UnInit() - 对话框未销毁: 使用上下文管理器()实现自动清理。
with MyDialog(...) as dlg: - Sizer元素父组件错误: Sizer中的所有控件必须属于同一个父面板。
- 绝对定位: 不要使用 或
SetPosition()做布局,始终使用Sizer。SetSize()
Cross-Platform Paths
跨平台路径
python
from platformdirs import user_config_dir, user_data_dir, user_cache_dir
config = user_config_dir("MyApp", "MyCompany") # %APPDATA% / ~/Library/... / ~/.config/
data = user_data_dir("MyApp", "MyCompany")
cache = user_cache_dir("MyApp", "MyCompany")python
from platformdirs import user_config_dir, user_data_dir, user_cache_dir
config = user_config_dir("MyApp", "MyCompany") # %APPDATA% / ~/Library/... / ~/.config/
data = user_data_dir("MyApp", "MyCompany")
cache = user_cache_dir("MyApp", "MyCompany")Testing Quick Reference
测试快速参考
bash
undefinedbash
undefinedRun all tests
运行所有测试
pytest
pytest
Run specific test file
运行指定测试文件
pytest tests/test_queue.py
pytest tests/test_queue.py
Run specific test
运行指定测试用例
pytest tests/test_queue.py::test_submit_job -v
pytest tests/test_queue.py::test_submit_job -v
With coverage
生成覆盖率报告
pytest --cov=mypackage --cov-report=term-missing
pytest --cov=mypackage --cov-report=term-missing
Stop on first failure
首次失败即停止
pytest -x
pytest -x
Show locals on failure
失败时展示局部变量
pytest -l
undefinedpytest -l
undefinedLogging Setup Template
日志配置模板
python
import logging
def setup_logging(level: int = logging.INFO) -> None:
logging.basicConfig(
level=level,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# Quiet noisy libraries
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)python
import logging
def setup_logging(level: int = logging.INFO) -> None:
logging.basicConfig(
level=level,
format="%(asctime)s %(name)s %(levelname)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# 降低噪杂库的日志级别
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)Desktop Accessibility Quick Reference
桌面无障碍功能快速参考
Platform API Summary
平台API汇总
| Platform | API | Python Binding |
|---|---|---|
| Windows | UI Automation | |
| Windows | MSAA/IAccessible2 | |
| macOS | NSAccessibility | |
| 平台 | API | Python绑定 |
|---|---|---|
| Windows | UI Automation | |
| Windows | MSAA/IAccessible2 | |
| macOS | NSAccessibility | |
wxPython Accessibility
wxPython无障碍配置
python
undefinedpython
undefinedSet accessible name (screen reader label)
设置无障碍名称(屏幕阅读器标签)
control.SetLabel("Descriptive Label")
control.SetLabel("Descriptive Label")
Set accessible description (supplementary info)
设置无障碍描述(补充信息)
Use wx.AccessibleDescription or wx.Accessible subclass
使用 wx.AccessibleDescription 或 wx.Accessible 子类
Keyboard navigation
键盘导航
control.SetFocus() # Move focus programmatically
panel.SetFocusIgnoringChildren() # Focus the panel itself
undefinedcontrol.SetFocus() # 编程式移动焦点
panel.SetFocusIgnoringChildren() # 聚焦面板本身
undefined