python

Python development rules for web applications, data work, machine learning, automation, APIs, and microservices. Python is a programming language commonly used for these tasks.

In plain words
What is it for?
Building Django, Flask, or FastAPI services, automation scripts, data projects, APIs, and other Python code.
Why use it?
They provide shared guidance for project layout, naming, formatting, dependencies, and common Python application structure.

Cursor rule for Cursor

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 rules/wangqiqi/cursor-ai-rules/python
Clone the repo
git clone --depth 1 https://github.com/wangqiqi/cursor-ai-rules

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 2,673 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.00000 $0.02673
Opus 5 $0.00000 $0.01337
Sonnet 5 $0.00000 $0.00535
Haiku 4.5 $0.00000 $0.00267

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

Security

Grade A, and why

python 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.

.cursor/rules/tech/python.mdc · 405 lines

How it starts

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

🐍 Python 开发规则

版本: v4.3.0 | 最后更新: 2026-01-15 | 作者: wangqiqi (https://github.com/wangqiqi)

🎯 适用场景

  • Django/Flask/FastAPI Web 应用开发
  • 数据科学和机器学习项目
  • 自动化脚本和工具开发
  • API 服务和微服务架构

🏗️ 项目结构

推荐的项目布局

my_project/
├── src/                    # 源代码目录
│   ├── __init__.py
│   ├── main.py            # 应用入口
│   └── my_module/         # 功能模块
│       ├── __init__.py
│       ├── models.py      # 数据模型
│       ├── views.py       # 视图/控制器
│       ├── services.py    # 业务逻辑
│       └── utils.py       # 工具函数
├── tests/                 # 测试目录
│   ├── __init__.py
│   ├── test_models.py
│   └── test_services.py
├── docs/                  # 文档
├── requirements.txt       # 依赖管理
├── pyproject.toml         # 项目配置 (现代)
├── setup.py              # 包安装配置
├── .env                  # 环境变量
├── .gitignore
└── README.md

📝 编码规范

PEP 8 合规

  • 行长度: 最多79个字符(Docstring 72个字符)
  • 缩进: 4个空格,无Tab
  • 命名: snake_case for 函数和变量,CamelCase for 类
# ✅ 推荐的命名和结构
class UserService:
    """用户服务类,处理用户相关的业务逻辑。"""

    def __init__(self, db_connection):
        self.db = db_connection
        self._cache = {}

    def get_user_by_id(self, user_id: int) -> Optional[User]:
        """根据用户ID获取用户信息。

        Args:
            user_id: 用户的唯一标识符

        Returns:
            用户对象,如果不存在则返回None

        Raises:
            ValueError: 当user_id无效时
        """
        if not isinstance(user_id, int) or user_id <= 0:
            raise ValueError("用户ID必须是正整数")

        # 检查缓存
        if user_id in self._cache:
            return self._cache[user_id]

        # 查询数据库
        user = self.db.query("SELECT * FROM users WHERE id = ?", user_id)

        # 更新缓存
        if user:
            self._cache[user_id] = user

        return user

类型注解 (Python 3.5+)

from typing import List, Dict, Optional, Union
from dataclasses import dataclass

@dataclass
class User:
    id: int
    name: str
    email: str
    is_active: bool = True

def process_users(users: List[User]) -> Dict[str, int]:
    """处理用户列表,返回统计信息。"""
    stats = {"total": 0, "active": 0}

    for user in users:
        stats["total"] += 1
        if user.is_active:
            stats["active"] += 1

    return stats

Read the full file on GitHub · 405 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 · 405 lines · 0 tokens per session scan A f73dd336f7df

Subscribe to this mod's changes

python is a cursor rule published in the GitHub repository wangqiqi/cursor-ai-rules (15 stars, last pushed 3mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 2,673 tokens. 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-30.