python-idioms

A set of guidelines for writing clear, safe, maintainable Python. It covers common language features, type annotations, standard-library choices, function design, exceptions, and resource handling.

In plain words
What is it for?
Use it when writing, reviewing, or refactoring Python functions, classes, and modules. It helps with containers, typing, dependencies, virtual environments, exceptions, and file or resource handling.
Why use it?
It helps avoid verbose C-style loops, shared mutable default values, overly broad exception handling, and code that is harder to check or maintain. The rules encourage Python’s built-in patterns where they fit.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/wade-devcode/awesome-coding-skills-cn/python-idioms
Any agent
npx skills add Wade-DevCode/awesome-coding-skills-cn --skill python-idioms
Clone the repo
git clone --depth 1 https://github.com/Wade-DevCode/awesome-coding-skills-cn

Made for: Claude Code, Codex.

Per session 21 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,099 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00021 $0.02099
Opus 5 $0.00010 $0.01050
Sonnet 5 $0.00004 $0.00420
Haiku 4.5 $0.00002 $0.00210

Measured 2d ago against content hash 1b8720890d92, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

python-idioms scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/python-idioms/SKILL.md · 148 lines

How it starts

The opening of the file, as written. The whole thing — 148 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python 惯用法

何时用

  • 写新的 Python 函数、类或模块时。
  • Review Python 代码、发现有 C 风格循环或裸 except 时。
  • 设计数据结构、选择容器类型时。
  • 配置项目依赖或虚拟环境时。
  • 给已有 Python 代码加类型注解或重构时。

核心规则

1. 用语言特性,不写 C 风格循环

规则: 优先使用列表/字典/集合推导式、enumeratezip、生成器表达式;凡是靠下标手动累加的循环,基本都有更地道的写法。

为什么: AI 生成 Python 代码时极容易退化成 Java/C 风格:for i in range(len(arr)): result.append(arr[i] * 2)。这种写法既啰嗦又容易因下标越界出 bug,而且完全没有利用 Python 的高阶抽象。读者一眼扫过去就知道这段代码不是"Python 人"写的。

怎么做:

  • 遍历并需要下标 → enumerate(seq),不要 range(len(seq))
  • 同时遍历两个序列 → zip(a, b),不要双重下标。
  • 构建新列表/字典 → 推导式;数据量大且只消费一次 → 生成器表达式(括号版)。
  • 需要累积结果 → 考虑 map/filter/itertools,但可读性优先于炫技。

2. 善用标准库与类型注解;函数职责单一,避免可变默认参数陷阱

规则: 能用标准库解决的不造轮子;所有公开函数加类型注解;函数只做一件事;默认参数值若是可变对象(list/dict/set)必须用 None 代替。

为什么: AI 常见错误之一是把可变对象直接当默认参数:def add_item(item, bucket=[]):——这个 bucket 在所有调用间共享,函数第二次调用时里面已经有上次留下的数据,是 Python 最经典的"幽灵 bug"。类型注解则让 mypy 在运行前就能发现大量错误。

怎么做:

  • 可变默认参数一律写 param: list | None = None,函数体内 if param is None: param = []
  • collections.defaultdictpathlib.Pathdataclasses.dataclass 代替手写字典嵌套、字符串拼路径、裸 __init__
  • 类型注解遵循 PEP 604(X | Y)和 PEP 585(list[int]),Python 3.10+ 不再需要从 typing 导入基础类型。

3. 异常用具体类型,资源用 with;不裸 except

规则: 捕获异常时必须指定类型(except ValueError),禁止裸 except:except Exception as e: pass;打开文件、网络连接、数据库游标等资源必须用 with 语句管理。

为什么:except 会吞掉 KeyboardInterruptSystemExit 等非异常信号,导致程序无法正常终止;同时把真正的 bug 掩盖掉,让问题在更下游以更难理解的形式爆发。AI 在不确定异常类型时倾向于写 except Exception,这是懒惰的防御,不是可靠的错误处理。

怎么做:

  • 明确知道可能抛什么 → 精确 except,必要时记录日志后重新 raise
  • 确实需要兜底 → except Exception as e: logger.error(...); raise —— 记录后重抛,不静默吞掉。
  • 所有有 close() 的对象 → with 语句;若对象不支持上下文管理器,用 contextlib.closing 包装。

4. 虚拟环境 + 锁定依赖;遵循 PEP 8 与项目既有风格

规则: 项目必须有虚拟环境(venv/poetry/uv);依赖版本必须锁定(requirements.txt 精确版本或 poetry.lock);代码风格服从 PEP 8,同时与项目已有风格保持一致,不随意引入新的格式规则。

为什么: AI 常见问题:在系统 Python 环境下直接 pip install,或者在 requirements.txt 里写 requests>=2.0(范围依赖),导致不同机器的依赖版本不同,代码在 CI 上跑通在生产上崩。另一类问题是在只用单引号的项目里突然改成双引号,污染 git blame,引起不必要的 review 争议。

Read the full file on GitHub · 148 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 148 lines · 21 tokens per session scan A 1b8720890d92

Subscribe to this mod's changes

python-idioms is a skill published in the GitHub repository Wade-DevCode/awesome-coding-skills-cn (6 stars, last pushed 2mo ago), licensed MIT. It adds 21 tokens to every session and 2,099 once invoked, about $0.0001 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories

chinese-git-workflow

国内 Git 平台配置参考——Gitee、Coding.net、极狐 GitLab、CNB 的 SSH/HTTPS/凭据/CI 接入差异与镜像同步配置。仅在用户显式 /chinese-git-workflow 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 69 tokens

brainstorming

在任何创造性工作之前必须使用此技能——创建功能、构建组件、添加功能或修改行为。在实现之前先探索用户意图、需求和设计。.

jnMetaCode/superpowers-zh · 40 tokens

chinese-code-review

中文 review 沟通参考——话术模板、分级标注(必须修复/建议修改/仅供参考)、国内团队常见反模式应对。仅在用户显式 /chinese-code-review 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 62 tokens

chinese-commit-conventions

中文 commit 与 changelog 配置参考——Conventional Commits 中文适配、commitlint/husky/commitizen 中文模板、conventional-changelog 中文配置。仅在用户显式 /chinese-commit-conventions 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 65 tokens

chinese-documentation

中文文档排版参考——中英文空格、全半角标点、术语保留、链接格式、中文文案排版指北约定。仅在用户显式 /chinese-documentation 时调用,不要根据上下文自动触发。.

jnMetaCode/superpowers-zh · 62 tokens

systematic-debugging

Skill "systematic-debugging" from jnMetaCode/superpowers-zh, covering 系统化调试, 概述, 铁律, 何时使用 and 四个阶段.

jnMetaCode/superpowers-zh · 24 tokens