python-best-practices
Comprehensive Python coding conventions and best practices. Use when the user asks about Python conventions, coding patterns, best practices, code style, anti-patterns, or "how should I write this" in Python.
- License 许可
- MIT
- 最近更新
- 2026-10-24
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- python-best-practices
- description
- Comprehensive Python coding conventions and best practices. Use when the user asks about Python conventions, coding patterns, best practices, code style, anti-patterns, or "how should I write this" in Python.
02 资源文件 1
- 参考文档.managed-skill.md251 B
03 SKILL.md 正文
MANAGED SKILL — Do not edit this file here. It is managed from an external source repository. To make changes, update the source and run "update my skills" to sync.
Python Best Practices
The canonical reference for Python coding conventions in this project. When in doubt about how to write Python, consult this skill.
Philosophy
The Zen of Python is not decoration — it drives real decisions:
- Beautiful is better than ugly — Name things clearly. Structure code so it reads top-down without jumping around.
- Explicit is better than implicit — Don't hide behavior in magic methods, decorators, or metaclasses unless the abstraction genuinely simplifies understanding.
- Simple is better than complex — If a function needs a paragraph to explain, it does too much. Split it.
- Flat is better than nested — Use early returns to avoid deep indentation. Prefer guard clauses over nested
if/elsetrees. - Readability counts — Code is read far more often than written. Optimize for the reader, not the writer.
- Errors should never pass silently — Catch specific exceptions. Log or re-raise. Never use bare
except:orexcept Exception: pass.
When two principles conflict, prefer the one that makes the code easier to understand six months from now.
Project Layout
- Use the src layout: source code in
src/{package_name}/, tests intests/. - Never put package code at the repository root.
- Test files mirror the source structure:
src/myapp/services/user.py→tests/test_services/test_user.pyortests/test_user_service.py. - Keep
__init__.pyminimal — use it for public API re-exports, not logic.
Imports
- Always at the top of the module. Never inside functions, methods, or conditional blocks.
- Use absolute imports:
from myapp.services.user import UserService, not relative imports. - Import order (enforced by ruff with isort rules):
- Standard library
- Third-party packages
- Local application imports
- Each group separated by a blank line.
- Import specific names (
from os.path import join) rather than entire modules when only one or two names are needed. Import the module (import os.path) when using many names from it.
Naming
- Variables and functions:
snake_case - Classes:
PascalCase - Constants:
UPPER_SNAKE_CASE - Private: prefix with single underscore (
_internal_helper) - Avoid abbreviations unless universally understood (
db,url,idare fine;usr_svc_mgris not). - Boolean variables and functions: use
is_,has_,can_,should_prefixes. A boolean namedactiveis ambiguous;is_activeis clear.
Functions and Methods
- Single responsibility: each function does one thing. If you describe it with "and", split it.
- Type hints on public APIs: all public functions and methods must have parameter and return type annotations.
- Docstrings on public APIs: one-line summary. Add detail only when the behavior is non-obvious.
- Prefer returning values over mutating arguments. If mutation is necessary, make it obvious in the function name (
update_user_status, notprocess_user). - Keep functions short — if a function exceeds ~30 lines, consider extracting helpers.
- Default arguments: never use mutable defaults (
def f(items=[]):). UseNoneand initialize inside.
Error Handling
- Catch specific exceptions, never bare
except:orexcept Exception:. - Never swallow exceptions silently — at minimum, log the error. Prefer re-raising or converting to a domain-specific exception.
- Use custom exceptions for domain errors. Inherit from a project-level base exception so callers can catch broadly when needed.
- Fail fast — validate inputs at the boundary (function entry, API endpoint, CLI argument parsing). Don't let invalid data propagate deep into the system.
- Context managers (
withstatements) for resource cleanup — files, connections, transactions.
# Good: specific exception, clear message, re-raise
try:
response = client.fetch(url)
except ConnectionError as exc:
logger.error("Failed to fetch %s: %s", url, exc)
raise ServiceUnavailableError(f"Upstream unreachable: {url}") from exc
# Bad: swallowing everything
try:
response = client.fetch(url)
except Exception:
pass
Code Quality
- Type hints on all new functions and class attributes. Use
from __future__ import annotationsfor modern syntax in older Python versions. - No obvious comments — comments explain "why", never "what". If the code needs a comment to explain what it does, rewrite the code to be clearer.
- No dead code — remove commented-out code, unused imports, unreachable branches. Version control is the history.
- DRY within reason — extract duplicated logic into functions, but don't over-abstract. Two occurrences may be coincidence; three is a pattern.
- Constants over magic values —
if retries > MAX_RETRIES:is clearer thanif retries > 3:.
Testing
- Framework: pytest (always).
- Real objects over mocks — exercise actual code paths whenever possible. Mocks are a last resort, not a convenience.
- Testing priority (strictly enforced):
- Real integrations and real code paths
responseslibrary for external HTTP calls (@responses.activate)factory-boyfor test data generation (SQLAlchemyModelFactory)- Pytest fixtures for reusable setup
unittest.mock.patchonly as absolute last resort (gRPC clients, etc.)
- One test, one behavior — each test function verifies exactly one thing.
- No conditional logic in tests — no
if/else,try/except,for,while, ternary operators inside test functions. - Descriptive test names:
test_<action>_<scenario>ortest_<what>_<expected_outcome>. - Use
parametrizeto avoid copy-paste duplication when multiple inputs share the same test logic. - Use
hypothesisfor property-based testing on validators, numeric calculations, and data parsing. - Tests are deterministic — no randomness, no dependency on external state, no time-sensitive assertions without freezing time.
- Keep test files under ~200 lines — split by concern when they grow.
For the full testing workflow (research, discuss, write), see the write-pytest skill.
Formatting and Linting
- Formatter: black (line length 88).
- Linter: ruff.
- Both are non-negotiable. Run them before every commit.
- Do not fight the formatter — if black produces output you dislike, restructure the code rather than adding
# fmt: off. - Ruff rules include: pyflakes (
F), pycodestyle (E), isort (I), and additional checks as configured inpyproject.toml.
Dependency Management
- Never install packages without using the project's package manager (uv or poetry).
- Always update the lockfile after adding or removing dependencies.
- Use dev dependency groups for test/lint/doc packages — they should not be in production dependencies.
- Pin versions in the lockfile, use compatible ranges in
pyproject.toml(e.g.,requests>=2.28,<3).
For the full dependency management workflow, see the manage-dependencies skill.
Forbidden Patterns
These are hard rules, not suggestions:
- Never use pydantic — not in any form (BaseModel, validators, Field, etc.).
- Never use FastAPI — not as a framework, not for a single endpoint.
- Never put imports inside functions or methods — all imports at module top level.
- Never use bare
except:— always catch specific exceptions. - Never use mutable default arguments —
def f(items=[]):is a bug waiting to happen. - Never use
from module import *— explicit imports only.
Anti-Patterns Catalog
Stringly-typed code
# Bad: status is a string, typos are silent bugs
if user.status == "actve": # typo, no error
grant_access(user)
# Good: use an enum or constant
class UserStatus:
ACTIVE = "active"
INACTIVE = "inactive"
if user.status == UserStatus.ACTIVE:
grant_access(user)
God function
# Bad: one function doing everything
def process_order(order):
validate_items(order.items)
calculate_totals(order)
check_inventory(order.items)
charge_payment(order.payment)
send_confirmation(order.customer)
update_analytics(order)
# ... 200 more lines
# Good: orchestrator delegates to focused functions
def process_order(order):
validated = validate_order(order)
charged = charge_order(validated)
fulfill_order(charged)
notify_customer(charged)
Nested conditionals
# Bad: deep nesting
def get_discount(user, order):
if user is not None:
if user.is_premium:
if order.total > 100:
return 0.2
else:
return 0.1
else:
return 0.0
else:
return 0.0
# Good: guard clauses, flat structure
def get_discount(user, order):
if user is None:
return 0.0
if not user.is_premium:
return 0.0
if order.total > 100:
return 0.2
return 0.1
Silent exception swallowing
# Bad: errors vanish
def fetch_user(user_id):
try:
return db.query(User).get(user_id)
except Exception:
return None
# Good: explicit handling
def fetch_user(user_id):
try:
return db.query(User).get(user_id)
except SQLAlchemyError as exc:
logger.error("Failed to fetch user %s: %s", user_id, exc)
raise
Mock-heavy tests
# Bad: testing the mocks, not the code
def test_create_user():
mock_db = Mock()
mock_validator = Mock(return_value=True)
mock_hasher = Mock(return_value="hashed")
service = UserService(mock_db, mock_validator, mock_hasher)
service.create_user("test@example.com", "password")
mock_db.save.assert_called_once()
# Good: real objects, real behavior
def test_create_user(dbsession):
service = UserService(dbsession)
user = service.create_user("test@example.com", "password")
assert user.email == "test@example.com"
assert dbsession.query(User).count() == 1
04 同仓库更多 Skills
write-pytest
Write pytest tests for any Python codebase. Use when the user asks to write tests, create tests, add tests, or test a module/service/endpoint/function. Framework-agnostic; routes to framework-specific helpers when signals are detected. Follows a research-then-discuss-then-write flow.
quality-assurance
Run quality assurance checks on the current chat session — pre-task validation, post-task checklist, and code review. Use when finishing a task, before committing, or when the user asks for a QA review.
python-developer
Python developer umbrella — installs Python coding conventions and bundles companion skills (best practices, testing, dependency management) in a single setup. Use when the user asks to set up Python development conventions, install Python skills, or says "set up Python development".
pyramid-library
Library Developer persona: developing standalone Pyramid extensions (own repo, own package) that expose includeme for external consumers. Use when the user builds a reusable Pyramid library, designs includeme for consumers, registers custom directives/tweens/request methods, or tests a library with a proper app.
pyramid-developer
Pyramid framework conventions — configuration/registry, module system with includeme, pyramid_services, models, Cornice REST, ACL authorization, and transactions. Use when setting up Pyramid development conventions for a project.
pyramid-core
Pyramid framework features reference — request methods, custom directives, events, tweens, exception views, view predicates, view derivers, callbacks, renderers, and static views. Use when the user asks about any Pyramid framework extension point.