agentleFS
quruhao4800quruhao4800/agent-workflow/skills/languages/python-patterns/SKILL.md

python-patterns

Skill1 starsChanged 6 months agoMITView on GitHub

General Python coding standards: naming, logging, exception handling, type hints, and project structure. Use for any Python project task.

  • Reads credentials

56 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use configure-ecc, nuxt4-patterns and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • royaluniondesign-sysSkill

    configure-ecc

    Interactive installer for Everything Claude Code — guides users through selecting and installing skills and rules to user-level or project-level directories, verifies paths, and optionally optimizes installed files.

    Also in 12 projects that use this

  • loulanyueSkill

    nuxt4-patterns

    Nuxt 4 app patterns for hydration safety, performance, route rules, lazy loading, and SSR-safe data fetching with useFetch and useAsyncData.

    Also in 10 projects that use this

  • RojiosSkill

    dart-flutter-patterns

    Production-ready Dart and Flutter patterns covering null safety, immutable state, async composition, widget architecture, popular state management frameworks (BLoC, Riverpod, Provider), GoRouter navigation, Dio networking, Freezed code generation, and clean architecture.

    Also in 7 projects that use this

  • royaluniondesign-sysSkill

    content-hash-cache-pattern

    Cache expensive file processing results using SHA-256 content hashes — path-independent, auto-invalidating, with service layer separation.

    Also in 16 projects that use this

  • TironFoxSkill

    agent-payment-x402

    Add x402 payment execution to AI agents — per-task budgets, spending controls, and non-custodial wallets via MCP tools. Use when agents need to pay for APIs, services, or other agents.

    Also in 6 projects that use this

  • TironFoxSkill

    openclaw-persona-forge

    为 OpenClaw AI Agent 锻造完整的龙虾灵魂方案。根据用户偏好或随机抽卡, 输出身份定位、灵魂描述(SOUL.md)、角色化底线规则、名字和头像生图提示词。 如当前环境提供已审核的生图 skill,可自动生成统一风格头像图片。 当用户需要创建、设计或定制 OpenClaw 龙虾灵魂时使用。 不适用于:微调已有 SOUL.md、非 OpenClaw 平台的角色设计、纯工具型无性格 Agent。 触发词:龙虾灵魂、虾魂、OpenClaw 灵魂、养虾灵魂、龙虾角色、龙虾定位、 龙虾剧本杀角色、龙虾游戏角色、龙虾 NPC、龙虾性格、龙虾背景故事、 lobster soul、lobster character、抽卡、随机龙虾、龙虾 SOUL、gacha。

    Also in 5 projects that use this

  • +1 more from royaluniondesign-sys

The file

We split this skill into the rules it gives an agent

3 rules. 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 53 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Never silently swallow exceptions.

    line 14
  2. Very specific:

    Never use print() to record application events.

    line 42
  3. Distinctive:

    Keep empty or limit to public re-exports — no business logic inside

    line 124

“Common” is measured: kept by at least 6 in 10 of the 53 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python Coding Patterns

Mandatory

Rules in this section block task completion when violated.

No Bare Except

Never silently swallow exceptions. A bare except: or except Exception: pass hides bugs and makes debugging impossible.

# BAD
try:
    result = process(data)
except:
    pass

# BAD — catches too broadly and discards the error
try:
    result = process(data)
except Exception:
    pass

# GOOD — catch specific exception, log with context, re-raise or handle
try:
    result = process(data)
except ValueError as e:
    logger.error("Invalid data in process: %s", e)
    raise
except IOError as e:
    logger.error("IO failure in process: %s", e)
    raise RuntimeError("Processing unavailable") from e

No print() for Logging

Never use print() to record application events. print() has no log level, no timestamp, and cannot be filtered or routed in production.

# BAD
print(f"Processing user {user_id}")
print("ERROR: " + str(e))

# GOOD
import logging
logger = logging.getLogger(__name__)

logger.info("Processing user %s", user_id)
logger.error("Failed to process user %s: %s", user_id, e)

Recommended

Rules in this section are flagged in review but do not block submission.

Naming Conventions (Python)

TargetConventionExample
Function / variablesnake_caseget_user, user_name
ClassPascalCaseUserService, OrderRequest
ConstantUPPER_SNAKE_CASEMAX_RETRIES = 3
Module / packagelowercase_underscoreuser_service.py
Private attributeleading __cache, _conn
Boolean variableis_ / has_ / can_ prefixis_active, has_permission

Type Hints

Recommended for all new code. Not a hard gate — absence does not block review. Static analysis (mypy, pyright) is optional but encouraged on CI.

# Recommended — explicit contracts
from typing import Optional

def get_user(user_id: int) -> Optional[User]:
    ...

def create_order(request: OrderRequest) -> OrderResponse:
    ...

# Acceptable when type is unambiguous from context
def _double(x):
    return x * 2

Function and File Size

  • Function body: ≤ 50 lines, cyclomatic complexity ≤ 10
  • Single file: ≤ 500 lines — split by responsibility when approaching the limit

Project Structure

Standard layout for a Python backend service:

project/
├── src/                    # optional src layout
│   ├── __init__.py
│   ├── api/                # route handlers / controllers
│   ├── services/           # business logic
│   ├── models/             # domain models / Pydantic schemas
│   ├── repositories/       # data access layer
│   └── config.py
├── tests/
│   ├── conftest.py         # shared fixtures
│   ├── unit/
│   └── integration/
├── requirements.txt        # or pyproject.toml / uv.lock
└── .env.example

__init__.py:

  • Required in each package directory for explicit package declaration
  • Keep empty or limit to public re-exports — no business logic inside

Package management is project-specific: pip + venv, Poetry, and uv are all acceptable. Do not prescribe a tool unless the project already has one established.


Logging

Obtain a module-level logger once per file. Never configure logging inside library/module code (only in application entry point).

import logging

# One logger per module — do this at module level
logger = logging.getLogger(__name__)


def process_order(order_id: int) -> None:
    logger.info("Processing order %s", order_id)

    try:
        result = _run(order_id)
        logger.info("Order %s completed: %s", order_id, result.status)
    except ProcessingError as e:
        # Pass exc_info=True (or the exception) to capture full traceback
        logger.error("Order %s failed: %s", order_id, e, exc_info=True)
        raise

Log level guide:

LevelUse when
DEBUGDeveloper diagnostics, verbose internal state
INFONormal operational events (started, completed, state changed)
WARNINGUnexpected but recoverable (retry attempted, fallback used)
ERROROperation failed, requires attention
CRITICALSystem cannot continue, immediate action required

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.