mirror of
https://github.com/sanjeed5/awesome-cursor-rules-mdc.git
synced 2026-11-30 23:04:59 +08:00
Regenerate all MDC rules with fresh Exa data and December 2025 best practices
- Refreshed all 241 library rules with current best practices - Updated Exa search results for all libraries with 2025 content - Fixed --regenerate-all flag logic to properly process all libraries - Removed duplicate astro entry in rules.json (merged tags) - Added missing docker.mdc and vim.mdc files - All rules now include modern patterns and anti-patterns - Updated with framework-specific recommendations for 2025 Technical improvements: - Fixed retry_failed_only logic in generate_mdc_files.py - Improved progress tracking for regeneration scenarios - Ensured proper handling of --refresh-exa flag
This commit is contained in:
+206
-195
@@ -1,207 +1,218 @@
|
||||
---
|
||||
description: Comprehensive best practices and coding standards for utilizing Pydantic effectively in Python projects, covering code organization, performance, security, and testing.
|
||||
globs: *.py
|
||||
description: Definitive guidelines for writing robust, maintainable, and performant pydantic models in Python, focusing on v2.12.5 best practices.
|
||||
globs: **/*.py
|
||||
---
|
||||
- **Model Definition:**
|
||||
- Use `BaseModel` to define data schemas with type annotations for clarity and automatic validation.
|
||||
- Prefer simple models that encapsulate a single concept to maintain readability and manageability.
|
||||
- Use nested models for complex data structures while ensuring each model has clear validation rules.
|
||||
- Always define a `Config` class within your model to control model behavior.
|
||||
# pydantic Best Practices
|
||||
|
||||
- **Validation and Error Handling:**
|
||||
- Implement built-in and custom validators to enforce data integrity.
|
||||
- Utilize `@field_validator` for field-specific rules and `@root_validator` for cross-field validation.
|
||||
- Ensure that validation errors are user-friendly and logged for debugging purposes.
|
||||
- Custom error messages should be informative and guide the user on how to correct the data.
|
||||
- Use `ValidationError` to catch and handle validation errors.
|
||||
Pydantic v2 is the standard for data validation in modern Python. Follow these rules to build type-safe, efficient, and maintainable data models.
|
||||
|
||||
- **Performance Optimization:**
|
||||
- Consider using lazy initialization and avoid redundant validation where data is already trusted.
|
||||
- Use Pydantic's configuration options to control when validation occurs, which can significantly enhance performance in high-throughput applications.
|
||||
- Use `model_rebuild` to dynamically rebuild models when related schema change.
|
||||
- Consider using `__slots__` in the `Config` class to reduce memory footprint.
|
||||
## 1. Model Naming and Organization
|
||||
|
||||
- **Code Organization and Structure:**
|
||||
- **Directory Structure:**
|
||||
- Adopt a modular structure: `src/`, `tests/`, `docs/`.
|
||||
- Models can reside in `src/models/`.
|
||||
- Validators in `src/validators/`.
|
||||
- Example:
|
||||
|
||||
project_root/
|
||||
├── src/
|
||||
│ ├── __init__.py
|
||||
│ ├── models/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── user.py
|
||||
│ │ ├── item.py
|
||||
│ ├── validators/
|
||||
│ │ ├── __init__.py
|
||||
│ │ ├── user_validators.py
|
||||
│ ├── main.py # Application entry point
|
||||
├── tests/
|
||||
│ ├── __init__.py
|
||||
│ ├── test_user.py
|
||||
│ ├── test_item.py
|
||||
├── docs/
|
||||
│ ├── ...
|
||||
├── .env
|
||||
├── pyproject.toml
|
||||
├── README.md
|
||||
|
||||
- **File Naming:**
|
||||
- Use snake_case for file names (e.g., `user_model.py`).
|
||||
- Name model files after the primary model they define (e.g., `user.py` for `UserModel`).
|
||||
- **Module Organization:**
|
||||
- Group related models and validators into separate modules.
|
||||
- Utilize `__init__.py` to make modules importable.
|
||||
- **Component Architecture:**
|
||||
- Employ a layered architecture (e.g., data access, business logic, presentation).
|
||||
- Pydantic models are primarily used in the data access layer.
|
||||
- **Code Splitting:**
|
||||
- Split large models into smaller, manageable components using composition.
|
||||
- Leverage inheritance judiciously.
|
||||
**Always use clear, singular nouns for models and group them in a dedicated `models/` package.** This improves discoverability and maintains a consistent project structure.
|
||||
|
||||
- **Common Patterns and Anti-patterns:**
|
||||
- **Design Patterns:**
|
||||
- **Data Transfer Object (DTO):** Pydantic models serve as DTOs.
|
||||
- **Factory Pattern:** Create model instances using factory functions for complex initialization.
|
||||
- **Repository Pattern:** Use repositories to abstract data access and validation logic.
|
||||
- **Recommended Approaches:**
|
||||
- Centralize validation logic in dedicated validator functions.
|
||||
- Utilize nested models for complex data structures.
|
||||
- Use `BaseSettings` for managing application settings.
|
||||
- **Anti-patterns:**
|
||||
- Embedding business logic directly into models.
|
||||
- Overly complex inheritance hierarchies.
|
||||
- Ignoring validation errors.
|
||||
- Performing I/O operations within validator functions.
|
||||
- **State Management:**
|
||||
- Use immutable models whenever possible to simplify state management.
|
||||
- Consider using state management libraries like `attrs` or `dataclasses` in conjunction with Pydantic for complex applications.
|
||||
- **Error Handling:**
|
||||
- Raise `ValidationError` exceptions when validation fails.
|
||||
- Provide informative error messages.
|
||||
- Log validation errors for debugging.
|
||||
❌ **BAD:**
|
||||
```python
|
||||
# In user_operations.py
|
||||
class UserData(BaseModel):
|
||||
name: str
|
||||
email: EmailStr
|
||||
|
||||
- **Performance Considerations:**
|
||||
- **Optimization Techniques:**
|
||||
- Use `model_rebuild` to recompile models when their schema changes.
|
||||
- Leverage `__slots__` in the `Config` class to reduce memory footprint.
|
||||
- Use the `@cached_property` decorator to cache expensive computations.
|
||||
- **Memory Management:**
|
||||
- Be mindful of large lists or dictionaries within models, as they can consume significant memory.
|
||||
- Use generators or iterators for processing large datasets.
|
||||
- **Efficient Data Parsing:**
|
||||
- Utilize `model_validate_json` and `model_validate` for efficient data parsing.
|
||||
- **Controlling Validation:**
|
||||
- Use `validate_default` and `validate_assignment` options in the `Config` class to control validation occurrence.
|
||||
# In users_api.py
|
||||
class UserRequest(BaseModel):
|
||||
name: str
|
||||
email: EmailStr
|
||||
```
|
||||
|
||||
- **Security Best Practices:**
|
||||
- **Common Vulnerabilities:**
|
||||
- Injection attacks (e.g., SQL injection) if model data is used directly in database queries.
|
||||
- Cross-site scripting (XSS) if model data is displayed in web pages without proper escaping.
|
||||
- Deserialization vulnerabilities if models are deserialized from untrusted sources.
|
||||
- **Input Validation:**
|
||||
- Always validate all incoming data using Pydantic models.
|
||||
- Use appropriate type annotations and constraints to restrict input values.
|
||||
- Sanitize input data to remove potentially harmful characters or sequences.
|
||||
- **Authentication and Authorization:**
|
||||
- Use authentication and authorization mechanisms to restrict access to sensitive data.
|
||||
- Implement role-based access control (RBAC) to grant different levels of access to different users.
|
||||
- **Data Protection:**
|
||||
- Encrypt sensitive data at rest and in transit.
|
||||
- Use secure storage mechanisms for storing API keys and other secrets.
|
||||
- Mask sensitive data in logs and error messages.
|
||||
- **Secure API Communication:**
|
||||
- Use HTTPS for all API communication.
|
||||
- Implement API rate limiting to prevent denial-of-service attacks.
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
# In models/user.py
|
||||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
- **Testing Approaches:**
|
||||
- **Unit Testing:**
|
||||
- Test individual models and validators in isolation.
|
||||
- Use parameterized tests to cover different input values and scenarios.
|
||||
- Verify that validation errors are raised correctly.
|
||||
- **Integration Testing:**
|
||||
- Test the interaction between models and other components of the application.
|
||||
- Use mock objects to simulate external dependencies.
|
||||
- **End-to-End Testing:**
|
||||
- Test the entire application flow from end to end.
|
||||
- Use automated testing tools to simulate user interactions.
|
||||
- **Test Organization:**
|
||||
- Organize tests into separate modules based on the component being tested.
|
||||
- Use descriptive test names to indicate the purpose of each test.
|
||||
- **Mocking and Stubbing:**
|
||||
- Use mock objects to simulate external dependencies such as databases or APIs.
|
||||
- Use stub objects to provide predefined responses for certain functions or methods.
|
||||
|
||||
- **Common Pitfalls and Gotchas:**
|
||||
- **Frequent Mistakes:**
|
||||
- Misusing Union Types: Using `Union` incorrectly can complicate type validation and handling.
|
||||
- Optional Fields without Default Values: Forgetting to provide a default value for optional fields can lead to `None` values causing errors in your application.
|
||||
- Incorrect Type Annotations: Assigning incorrect types to fields can cause validation to fail. For example, using `str` for a field that should be an `int`.
|
||||
- **Edge Cases:**
|
||||
- Handling complex validation logic with dependencies between fields.
|
||||
- Dealing with large or deeply nested data structures.
|
||||
- Handling different input formats (e.g., JSON, CSV).
|
||||
- **Version-Specific Issues:**
|
||||
- Be aware of breaking changes between Pydantic versions.
|
||||
- Consult the Pydantic documentation for migration guides.
|
||||
- **Compatibility Concerns:**
|
||||
- Ensure compatibility between Pydantic and other libraries used in your project.
|
||||
- Be mindful of potential conflicts with other validation libraries.
|
||||
|
||||
- **Tooling and Environment:**
|
||||
- **Development Tools:**
|
||||
- Use a code editor or IDE with Pydantic support (e.g., VS Code with the Pylance extension).
|
||||
- Use a static type checker like MyPy to catch type errors.
|
||||
- Use a linter like Flake8 or Pylint to enforce code style.
|
||||
- **Build Configuration:**
|
||||
- Use a build tool like Poetry or Pipenv to manage dependencies.
|
||||
- Specify Pydantic as a dependency in your project's configuration file.
|
||||
- **Linting and Formatting:**
|
||||
- Configure a linter and formatter to enforce consistent code style.
|
||||
- Use pre-commit hooks to automatically run linters and formatters before committing code.
|
||||
- **Deployment:**
|
||||
- Use a deployment platform that supports Python applications (e.g., Heroku, AWS Elastic Beanstalk, Docker).
|
||||
- Configure your deployment environment to install Pydantic and its dependencies.
|
||||
- **CI/CD:**
|
||||
- Integrate Pydantic tests into your CI/CD pipeline.
|
||||
- Automatically run tests and linters on every commit.
|
||||
|
||||
- **Getting Started with Pydantic:**
|
||||
- Install Pydantic with `pip install pydantic`
|
||||
- Define your data models using `BaseModel` and type hints
|
||||
- Validate your data by instantiating the data models
|
||||
- Handle validation errors using `try...except ValidationError`
|
||||
|
||||
- **Example:**
|
||||
python
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from typing import List, Optional
|
||||
|
||||
class Address(BaseModel):
|
||||
street: str
|
||||
city: str
|
||||
zip_code: Optional[str] = None
|
||||
|
||||
class User(BaseModel):
|
||||
class User(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
email: str
|
||||
addresses: List[Address]
|
||||
email: EmailStr
|
||||
```
|
||||
|
||||
try:
|
||||
user_data = {
|
||||
"id": 1,
|
||||
"name": "John Doe",
|
||||
"email": "invalid-email",
|
||||
"addresses": [{
|
||||
"street": "123 Main St",
|
||||
"city": "Anytown"
|
||||
}]
|
||||
}
|
||||
user = User(**user_data)
|
||||
print(user)
|
||||
except ValidationError as e:
|
||||
print(e.json())
|
||||
## 2. Strict Typing and Immutability
|
||||
|
||||
**Prefer concrete types over `Any`. Use `Strict*` types when no coercion is acceptable. Enable `validate_assignment=True` for mutable models, or `frozen=True` for immutable models.** Immutability is generally preferred for data models to prevent unexpected state changes.
|
||||
|
||||
❌ **BAD:**
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from typing import Any
|
||||
|
||||
class Item(BaseModel):
|
||||
quantity: Any # Allows "5" or 5
|
||||
price: float # Allows "10.5" or 10.5
|
||||
```
|
||||
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
from pydantic import BaseModel, StrictInt, StrictFloat, ConfigDict
|
||||
|
||||
class ImmutableItem(BaseModel):
|
||||
model_config = ConfigDict(frozen=True) # Makes instances immutable
|
||||
id: int
|
||||
name: str
|
||||
quantity: StrictInt # Only accepts int, "5" will fail
|
||||
price: StrictFloat # Only accepts float, "10.5" will fail
|
||||
|
||||
class MutableUser(BaseModel):
|
||||
model_config = ConfigDict(validate_assignment=True) # Validates on update
|
||||
name: str
|
||||
age: int
|
||||
|
||||
user = MutableUser(name="Alice", age=30)
|
||||
user.age = "31" # This will raise a ValidationError
|
||||
```
|
||||
|
||||
## 3. Safe Default Values
|
||||
|
||||
**Never use mutable objects (lists, dicts, sets) as direct default values.** This leads to shared state across instances. Always use `default_factory` or `Field(default_factory=...)`.
|
||||
|
||||
❌ **BAD:**
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
tags: list = [] # Shared list across all Product instances
|
||||
```
|
||||
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class Product(BaseModel):
|
||||
name: str
|
||||
tags: list[str] = Field(default_factory=list) # Each instance gets a new list
|
||||
```
|
||||
|
||||
## 4. Custom Validation Logic
|
||||
|
||||
**Use `@field_validator` for single-field validation and `@model_validator` for cross-field validation.** Keep validation logic concise and focused within the model definition. Extract complex business logic to separate service layers.
|
||||
|
||||
❌ **BAD:**
|
||||
```python
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
class Event(BaseModel):
|
||||
start_time: int
|
||||
end_time: int
|
||||
|
||||
def __post_init__(self): # Not a Pydantic v2 pattern
|
||||
if self.start_time >= self.end_time:
|
||||
raise ValueError("Start time must be before end time")
|
||||
```
|
||||
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
from pydantic import BaseModel, ValidationError, field_validator, model_validator
|
||||
from typing import Self
|
||||
|
||||
class Event(BaseModel):
|
||||
start_time: int
|
||||
end_time: int
|
||||
|
||||
@field_validator('start_time')
|
||||
@classmethod
|
||||
def check_start_time_positive(cls, v: int) -> int:
|
||||
if v < 0:
|
||||
raise ValueError("Start time must be positive")
|
||||
return v
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_time_order(self) -> Self:
|
||||
if self.start_time >= self.end_time:
|
||||
raise ValueError("Start time must be before end time")
|
||||
return self
|
||||
|
||||
try:
|
||||
Event(start_time=10, end_time=5)
|
||||
except ValidationError as e:
|
||||
print(e) # Shows 'Start time must be before end time'
|
||||
```
|
||||
|
||||
## 5. Settings Management
|
||||
|
||||
**Store application configuration in `pydantic_settings.BaseSettings` subclasses.** This automatically validates environment variables and ensures secrets are handled securely (e.g., with `SecretStr`).
|
||||
|
||||
❌ **BAD:**
|
||||
```python
|
||||
# config.py
|
||||
API_KEY = os.getenv("MY_API_KEY", "default_secret")
|
||||
DATABASE_URL = "sqlite:///./test.db"
|
||||
```
|
||||
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
# settings.py
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from pydantic import SecretStr
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore') # Load from .env, ignore unknown env vars
|
||||
|
||||
api_key: SecretStr
|
||||
database_url: str = "sqlite:///./test.db"
|
||||
|
||||
# Usage:
|
||||
settings = Settings()
|
||||
print(settings.api_key.get_secret_value()) # Access secret value safely
|
||||
```
|
||||
|
||||
## 6. Editor Integration (VS Code / Pylance)
|
||||
|
||||
**Configure VS Code with Pylance (`Type Checking Mode: strict`) to get real-time autocompletion and type error diagnostics.** For intentional Pydantic coercions that Pylance flags, use specific ignore comments or `cast`.
|
||||
|
||||
❌ **BAD:**
|
||||
```python
|
||||
# No Pylance, or Pylance in 'off' mode. Misses errors early.
|
||||
# Or, using general # type: ignore for all lines with Pydantic coercion.
|
||||
from pydantic import BaseModel
|
||||
class User(BaseModel):
|
||||
age: int
|
||||
user = User(age='23') # No error shown, but Pylance could warn
|
||||
```
|
||||
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
# VS Code settings: "python.analysis.typeCheckingMode": "strict"
|
||||
from pydantic import BaseModel
|
||||
from typing import cast
|
||||
|
||||
class User(BaseModel):
|
||||
age: int
|
||||
|
||||
user_str_age = User(age='23') # Pylance will flag this as str -> int, which Pydantic handles.
|
||||
# If you want to silence Pylance for this specific, known coercion:
|
||||
user_str_age_ignored = User(age='23') # pyright: ignore[reportGeneralTypeIssues]
|
||||
# Or explicitly cast if you prefer:
|
||||
user_str_age_casted = User(age=cast(int, '23'))
|
||||
```
|
||||
|
||||
## 7. Common Pitfalls
|
||||
|
||||
**Avoid field names that collide with Python keywords or Pydantic internal attributes.** This can lead to unexpected behavior or validation errors.
|
||||
|
||||
❌ **BAD:**
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
class BadModel(BaseModel):
|
||||
int: Optional[int] = None # 'int' is a built-in type, causes collision
|
||||
model_config: str = "some_config" # Collides with Pydantic's model_config
|
||||
```
|
||||
|
||||
✅ **GOOD:**
|
||||
```python
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
class GoodModel(BaseModel):
|
||||
integer_value: Optional[int] = None
|
||||
custom_config_name: str = "some_config"
|
||||
```
|
||||
Reference in New Issue
Block a user