代码风格检查与自动格式化。Use when (1) 配置 linter/formatter, (2) 修复代码风格问题, (3) 设置 pre-commit hooks, (4) 统一团队代码风格
# pyproject.toml
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"N", # pep8-naming
"UP", # pyupgrade
]
ignore = ["E501"] # Line too long (handled by formatter)
[tool.mypy]
python_version = "3.10"
strict = true
warn_return_any = true
warn_unused_configs = true
# Format code
ruff format .
# Check and fix linting issues
ruff check --fix .
# Type check
mypy src/
# Run all checks
ruff format . && ruff check --fix . && mypy src/
// eslint.config.js
export default [
{
files: ["**/*.{ts,tsx}"],
rules: {
"no-console": "warn",
"no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "error",
"react-hooks/rules-of-hooks": "error",
},
},
];
// .prettierrc
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
# Format code
npm run format
# or
npx prettier --write "src/**/*.{ts,tsx}"
# Lint and fix
npm run lint
# or
npx eslint --fix "src/**/*.{ts,tsx}"
# Type check
npx tsc --noEmit
# Python
class UserService: # PascalCase
MAX_RETRIES = 3 # UPPER_SNAKE_CASE
def get_user(self): # snake_case
user_id = 123 # snake_case
return user_id
// TypeScript
class UserService {
// PascalCase
private readonly maxRetries = 3; // camelCase
getUser(): User {
// camelCase
const userId = 123; // camelCase
return user;
}
}
# Python: Sorted by Ruff (isort)
import os
import sys
from pathlib import Path
import requests
from fastapi import FastAPI
from src.core.models import User
from src.services.auth import AuthService
// TypeScript: Sorted by ESLint
import { useState, useEffect } from "react";
import type { User } from "@/types";
import { Button } from "@/components/ui/button";
import { authService } from "@/services/auth";
# Always annotate function signatures
def get_user(user_id: int) -> User | None:
"""Get user by ID."""
return db.query(User).get(user_id)
# Use modern syntax (Python 3.10+)
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
// Prefer explicit types for public APIs
function getUser(userId: number): User | null {
return db.users.find(userId);
}
// Use type inference for locals
const users = await fetchUsers(); // Type inferred
def calculate_score(
user_id: int,
weights: dict[str, float],
normalize: bool = True
) -> float:
"""Calculate weighted score for user.
Args:
user_id: User identifier
weights: Feature weights mapping
normalize: Whether to normalize to [0, 1]
Returns:
Calculated score
Raises:
ValueError: If user not found
"""
pass
/**
* Calculate weighted score for user
*
* @param userId - User identifier
* @param weights - Feature weights mapping
* @param normalize - Whether to normalize to [0, 1]
* @returns Calculated score
* @throws {Error} If user not found
*/
function calculateScore(
userId: number,
weights: Record<string, number>,
normalize = true,
): number {
// ...
}
# .pre-commit-config.yaml