python-development

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Development Skill

Python开发技能

Reference data for the Developer Hub, Python Specialist, and wxPython Specialist agents.
供开发者中心、Python专家Agent和wxPython专家Agent使用的参考数据。

Python Version Quick Reference

Python版本快速参考

VersionKey FeaturesEOL
3.10
match/case
,
X | Y
unions,
ParamSpec
Oct 2026
3.11Exception groups,
Self
type,
tomllib
, faster CPython
Oct 2027
3.12Type parameter syntax
def f[T]()
,
@override
, f-string nesting
Oct 2028
3.13Experimental free-threaded mode, improved error messagesOct 2029
3.14
async pdb.set_trace_async()
, template strings (PEP 750)
Oct 2030
版本核心特性停止支持时间
3.10
match/case
X | Y
联合类型、
ParamSpec
2026年10月
3.11异常组、
Self
类型、
tomllib
、性能更快的CPython
2027年10月
3.12类型参数语法
def f[T]()
@override
、f-string嵌套
2028年10月
3.13实验性无全局解释器锁模式、优化的错误提示2029年10月
3.14
async pdb.set_trace_async()
、模板字符串(PEP 750)
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 = true
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 = true

PyInstaller 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
  • accessible_output2
    (for a11y desktop apps)
  • keyring.backends
    (for credential storage)
  • platformdirs
  • httpx._transports
    /
    httpcore._backends
  • encodings
    (always needed)
  • pkg_resources.extern
  • accessible_output2
    (无障碍桌面应用使用)
  • keyring.backends
    (凭证存储使用)
  • platformdirs
  • httpx._transports
    /
    httpcore._backends
  • encodings
    (始终需要导入)

wxPython Quick Reference

wxPython 快速参考

Sizer Cheat Sheet

Sizer速查表

SizerWhen to Use
wx.BoxSizer(wx.VERTICAL)
Stack items top-to-bottom
wx.BoxSizer(wx.HORIZONTAL)
Lay items left-to-right
wx.GridBagSizer(vgap, hgap)
Form layouts with labels + controls
wx.FlexGridSizer(rows, cols, vgap, hgap)
Even grid layouts
wx.WrapSizer
Flow layout that wraps
wx.StaticBoxSizer(wx.VERTICAL, parent, "Label")
Grouped controls with border
Sizer使用场景
wx.BoxSizer(wx.VERTICAL)
从上到下堆叠元素
wx.BoxSizer(wx.HORIZONTAL)
从左到右排列元素
wx.GridBagSizer(vgap, hgap)
带标签+控件的表单布局
wx.FlexGridSizer(rows, cols, vgap, hgap)
均匀网格布局
wx.WrapSizer
可自动换行的流式布局
wx.StaticBoxSizer(wx.VERTICAL, parent, "Label")
带边框的分组控件

Thread-Safe GUI Updates

线程安全的GUI更新

python
undefined
python
undefined

From 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
undefined
self.status_bar.SetStatusText("Done") # 会导致崩溃或数据损坏
undefined

Standard IDs

标准ID

IDPurpose
wx.ID_OK
OK button
wx.ID_CANCEL
Cancel button
wx.ID_SAVE
Save action
wx.ID_OPEN
Open action
wx.ID_EXIT
Exit / Quit
wx.ID_HELP
Help action
wx.ID_NEW
New document
wx.ID_UNDO
/
wx.ID_REDO
Undo / Redo
ID用途
wx.ID_OK
确认按钮
wx.ID_CANCEL
取消按钮
wx.ID_SAVE
保存操作
wx.ID_OPEN
打开操作
wx.ID_EXIT
退出操作
wx.ID_HELP
帮助操作
wx.ID_NEW
新建文档
wx.ID_UNDO
/
wx.ID_REDO
撤销/重做

Event Types

事件类型

EventTrigger
wx.EVT_BUTTON
Button click
wx.EVT_MENU
Menu item selected
wx.EVT_CLOSE
Window close requested
wx.EVT_SIZE
Window resized
wx.EVT_TIMER
Timer fired
wx.EVT_TEXT
Text control content changed
wx.EVT_LIST_ITEM_SELECTED
List item selected
wx.EVT_TREE_SEL_CHANGED
Tree selection changed
wx.EVT_UPDATE_UI
UI state update check
事件触发条件
wx.EVT_BUTTON
按钮点击
wx.EVT_MENU
菜单项被选中
wx.EVT_CLOSE
收到窗口关闭请求
wx.EVT_SIZE
窗口大小调整
wx.EVT_TIMER
计时器触发
wx.EVT_TEXT
文本控件内容变更
wx.EVT_LIST_ITEM_SELECTED
列表项被选中
wx.EVT_TREE_SEL_CHANGED
树形控件选中项变更
wx.EVT_UPDATE_UI
UI状态更新检查

Common Pitfalls

常见陷阱

Python

Python

  • Mutable default arguments:
    def f(items=[])
    shares the list across calls. Use
    None
    and create inside.
  • Late binding closures:
    lambda: x
    in a loop captures the variable, not the value. Use
    lambda x=x: x
    .
  • Circular imports: Move imports inside functions, use
    TYPE_CHECKING
    block, or restructure modules.
  • field()
    outside dataclass:
    field()
    is only valid inside
    @dataclass
    classes. Use plain type annotations elsewhere.
  • is
    vs
    ==
    :
    is
    checks identity,
    ==
    checks equality. Use
    is
    only for
    None
    ,
    True
    ,
    False
    .
  • String concatenation in loops: Use
    "".join()
    or
    io.StringIO
    instead.
  • 可变默认参数:
    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
    wx.CallAfter()
    or
    wx.PostEvent()
    .
  • Missing
    event.Skip()
    :
    Other handlers won't fire. Call
    event.Skip()
    unless you intentionally consume the event.
  • Timer not stopped: Stop timers in
    EVT_CLOSE
    handler to prevent callbacks after destruction.
  • AUI not uninitialized: Call
    _mgr.UnInit()
    in close handler.
  • Dialog not destroyed: Use context managers (
    with MyDialog(...) as dlg:
    ) for automatic cleanup.
  • Wrong parent for sizer items: All controls in a sizer must have the same parent panel.
  • Absolute positioning: Never use
    SetPosition()
    or
    SetSize()
    for layout. Always use sizers.
  • 在工作线程操作GUI: 始终使用
    wx.CallAfter()
    wx.PostEvent()
  • 遗漏
    event.Skip()
    其他事件处理器不会被触发,除非你有意消费该事件,否则需要调用
    event.Skip()
  • 未停止计时器:
    EVT_CLOSE
    处理器中停止计时器,避免窗口销毁后回调触发异常。
  • AUI未初始化销毁: 在关闭处理器中调用
    _mgr.UnInit()
  • 对话框未销毁: 使用上下文管理器(
    with MyDialog(...) as dlg:
    )实现自动清理。
  • Sizer元素父组件错误: Sizer中的所有控件必须属于同一个父面板。
  • 绝对定位: 不要使用
    SetPosition()
    SetSize()
    做布局,始终使用Sizer。

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
undefined
bash
undefined

Run 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
undefined
pytest -l
undefined

Logging 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汇总

PlatformAPIPython Binding
WindowsUI Automation
comtypes
+
UIAutomationCore
WindowsMSAA/IAccessible2
pyia2
,
comtypes
macOSNSAccessibility
pyobjc-framework-Cocoa
平台APIPython绑定
WindowsUI Automation
comtypes
+
UIAutomationCore
WindowsMSAA/IAccessible2
pyia2
comtypes
macOSNSAccessibility
pyobjc-framework-Cocoa

wxPython Accessibility

wxPython无障碍配置

python
undefined
python
undefined

Set 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
undefined
control.SetFocus() # 编程式移动焦点 panel.SetFocusIgnoringChildren() # 聚焦面板本身
undefined