python

Python coding guidelines and best practices. Use when writing, reviewing, or refactoring Python code. Enforces PEP 8 style, syntax validation via py_compile, unit test execution, modern Python versions only (no EOL), uv for dependency management when available, and idiomatic Pythonic patterns.

3,891 stars

Best use case

python is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Python coding guidelines and best practices. Use when writing, reviewing, or refactoring Python code. Enforces PEP 8 style, syntax validation via py_compile, unit test execution, modern Python versions only (no EOL), uv for dependency management when available, and idiomatic Pythonic patterns.

Teams using python should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/python/SKILL.md --create-dirs "https://raw.githubusercontent.com/openclaw/skills/main/skills/adarshdigievo/python/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/python/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How python Compares

Feature / AgentpythonStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Python coding guidelines and best practices. Use when writing, reviewing, or refactoring Python code. Enforces PEP 8 style, syntax validation via py_compile, unit test execution, modern Python versions only (no EOL), uv for dependency management when available, and idiomatic Pythonic patterns.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Python Coding Guidelines

## Code Style (PEP 8)

- 4 spaces for indentation (never tabs)
- Max line length: 88 chars (Black default) or 79 (strict PEP 8)
- Two blank lines before top-level definitions, one within classes
- Imports: stdlib → third-party → local, alphabetized within groups
- Snake_case for functions/variables, PascalCase for classes, UPPER_CASE for constants

## Before Committing

```bash
# Syntax check (always)
python -m py_compile *.py

# Run tests if present
python -m pytest tests/ -v 2>/dev/null || python -m unittest discover -v 2>/dev/null || echo "No tests found"

# Format check (if available)
ruff check . --fix 2>/dev/null || python -m black --check . 2>/dev/null
```

## Python Version

- **Minimum:** Python 3.10+ (3.9 EOL Oct 2025)
- **Target:** Python 3.11-3.13 for new projects
- Never use Python 2 syntax or patterns
- Use modern features: match statements, walrus operator, type hints

## Dependency Management

Check for uv first, fall back to pip:
```bash
# Prefer uv if available
if command -v uv &>/dev/null; then
    uv pip install <package>
    uv pip compile requirements.in -o requirements.txt
else
    pip install <package>
fi
```

For new projects with uv: `uv init` or `uv venv && source .venv/bin/activate`

## Pythonic Patterns

```python
# ✅ List/dict comprehensions over loops
squares = [x**2 for x in range(10)]
lookup = {item.id: item for item in items}

# ✅ Context managers for resources
with open("file.txt") as f:
    data = f.read()

# ✅ Unpacking
first, *rest = items
a, b = b, a  # swap

# ✅ EAFP over LBYL
try:
    value = d[key]
except KeyError:
    value = default

# ✅ f-strings for formatting
msg = f"Hello {name}, you have {count} items"

# ✅ Type hints
def process(items: list[str]) -> dict[str, int]:
    ...

# ✅ dataclasses/attrs for data containers
from dataclasses import dataclass

@dataclass
class User:
    name: str
    email: str
    active: bool = True

# ✅ pathlib over os.path
from pathlib import Path
config = Path.home() / ".config" / "app.json"

# ✅ enumerate, zip, itertools
for i, item in enumerate(items):
    ...
for a, b in zip(list1, list2, strict=True):
    ...
```

## Anti-patterns to Avoid

```python
# ❌ Mutable default arguments
def bad(items=[]):  # Bug: shared across calls
    ...
def good(items=None):
    items = items or []

# ❌ Bare except
try:
    ...
except:  # Catches SystemExit, KeyboardInterrupt
    ...
except Exception:  # Better
    ...

# ❌ Global state
# ❌ from module import * 
# ❌ String concatenation in loops (use join)
# ❌ == None (use `is None`)
# ❌ len(x) == 0 (use `not x`)
```

## Testing

- Use pytest (preferred) or unittest
- Name test files `test_*.py`, test functions `test_*`
- Aim for focused unit tests, mock external dependencies
- Run before every commit: `python -m pytest -v`

## Docstrings

```python
def fetch_user(user_id: int, include_deleted: bool = False) -> User | None:
    """Fetch a user by ID from the database.
    
    Args:
        user_id: The unique user identifier.
        include_deleted: If True, include soft-deleted users.
    
    Returns:
        User object if found, None otherwise.
    
    Raises:
        DatabaseError: If connection fails.
    """
```

## Quick Checklist

- [ ] Syntax valid (`py_compile`)
- [ ] Tests pass (`pytest`)
- [ ] Type hints on public functions
- [ ] No hardcoded secrets
- [ ] f-strings, not `.format()` or `%`
- [ ] `pathlib` for file paths
- [ ] Context managers for I/O
- [ ] No mutable default args

Related Skills

micropython-skills/sensor

3891
from openclaw/skills

MicroPython sensor reading — DHT11/22, BME280, MPU6050, ADC, ultrasonic HC-SR04, photoresistor, generic I2C sensors.

Coding & Development

micropython-skills/network

3891
from openclaw/skills

MicroPython networking — WiFi STA/AP, HTTP requests, MQTT pub/sub, BLE, NTP time sync, WebSocket.

Coding & Development

micropython-skills/diagnostic

3891
from openclaw/skills

MicroPython device diagnostics — system info, I2C/SPI bus scan, pin state, filesystem, memory, performance benchmarks.

Embedded Systems & IoT

micropython-skills/algorithm

3891
from openclaw/skills

MicroPython on-device algorithms — PID controller, moving average, Kalman filter, state machine, task scheduler, data logger.

Coding & Development

micropython-skills/actuator

3891
from openclaw/skills

MicroPython actuator control — GPIO output, PWM (LED/servo/motor), stepper motor, WS2812 NeoPixel, buzzer.

Internet of Things

micropython-skills

3891
from openclaw/skills

Program and interact with embedded development boards (ESP32, ESP32-S3, ESP32-C3, ESP8266, NodeMCU, Raspberry Pi Pico, RP2040, STM32) through real-time REPL. This skill turns microcontroller hardware into an AI-programmable co-processor — read sensors, control actuators, flash firmware, diagnose devices, and deploy algorithms. Trigger when the user mentions any dev board or hardware interaction: ESP32, ESP8266, NodeMCU, Pico, 开发板, 板子, 单片机, 嵌入式, microcontroller, development board, sensor reading, GPIO, LED, motor, relay, I2C, SPI, UART, ADC, PWM, servo, DHT, BME280, temperature sensor, 传感器, 读传感器, 控制电机, 继电器, flash firmware, 烧录, 刷固件, 刷机, mpremote, MicroPython, IoT, MQTT, WiFi on board, 设备没反应, device not responding, or any task involving programming or controlling a physical microcontroller board.

Embedded Development

Telegram Shop Bot Developer - Python

3891
from openclaw/skills

I develop fully-featured Telegram shop bots using Python. My bots manage products, orders, and customers professionally.

python-code-review

3891
from openclaw/skills

Reviews Python code for type safety, async patterns, error handling, and common mistakes. Use when reviewing .py files, checking type hints, async/await usage, or exception handling.

pythongo

3891
from openclaw/skills

answer questions about pythongo code, docs, callbacks, errors, modules, functions, marketcenter, paramsmap, instrument_id, exchange, kline data, and strategy examples. use when the user asks about pythongo implementation, behavior, interfaces, usage, installation, faq, or wants pythongo code examples based on the bundled codebase, docs_indexed, docs_normalized, examples.md, and pyi reference markdown files.

bocha-search-python

3891
from openclaw/skills

博查搜索 (Bocha Search) 的 Python 实现技能,提供增强的网页搜索能力。当用户需要通过博查 AI 搜索 API 进行网页搜索、获取联网信息、查找最新资讯或中文内容时使用此技能。与现有的 JavaScript 版本相比,本技能提供更稳定的连接、更灵活的输出格式(原始 JSON/Brave 兼容格式/Markdown)、更好的错误处理和重试机制。适用于 AI Agent 需要联网搜索、RAG 应用获取网页摘要、中文内容检索等场景。

strava-python

3891
from openclaw/skills

Query Strava activities, stats, and workout data using Python/stravalib with interactive setup

Li_python_sec_check

3891
from openclaw/skills

Python 安全规范检查工具 - 基于 CloudBase 规范 + 腾讯安全指南 + LLM 智能分析(LLM 功能默认禁用,本地执行优先)