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:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+198 -192
View File
@@ -1,239 +1,245 @@
---
description: This rule provides guidance on best practices for using setuptools in Python projects, covering code organization, performance, security, testing, and common pitfalls.
globs: **/setup.py
description: This guide defines best practices for configuring Python packages using setuptools, emphasizing modern, declarative `pyproject.toml` workflows for robust and maintainable projects.
globs: **/*.py
---
# setuptools Best Practices
This document outlines best practices for using `setuptools` in Python projects. Following these guidelines ensures maintainable, performant, and secure code.
`setuptools` is the de-facto standard for Python packaging. This guide outlines the definitive, modern approach to configuring your Python projects, prioritizing declarative `pyproject.toml` files, automated versioning, and clear dependency management. Adhere to these rules for consistent, maintainable, and standards-compliant package distributions.
## Library Information:
- Name: setuptools
- Tags: development, build-tool, python, packaging
## 1. Code Organization and Structure
## 1. Code Organization and Structure:
Always use the `src/` layout for your package source code. This clearly separates your package's importable code from project-level files (like `pyproject.toml`, `README.md`, `tests/`).
- **Directory Structure:**
- At the root:
- `setup.py`: The main setup script.
- `setup.cfg`: Configuration file for `setup.py` (optional but recommended).
- `pyproject.toml`: Build system configuration (modern approach).
- `README.md` or `README.rst`: Project description.
- `LICENSE.txt`: License information.
- `.gitignore`: Specifies intentionally untracked files that Git should ignore.
- A top-level package directory (e.g., `my_package`):
- `my_package/`:
- `__init__.py`: Makes the directory a Python package.
- `module1.py`: Module containing code.
- `module2.py`: Another module.
- `data/`: Directory for package data (optional).
- `tests/`:
- `test_module1.py`: Unit tests for `module1.py`.
- `test_module2.py`: Unit tests for `module2.py`.
- `conftest.py`: Configuration file for pytest.
- `__init__.py` (optional).
- `docs/` (optional):
- Project documentation (e.g., using Sphinx).
❌ BAD: Flat layout
```
my_package/
├── __init__.py
├── module.py
├── pyproject.toml
└── tests/
```
- **File Naming Conventions:**
- Python modules: `module_name.py` (snake_case).
- Test files: `test_module_name.py` or `module_name_test.py`.
- Package directories: `package_name/` (lowercase).
- Configuration files: `setup.cfg`, `pyproject.toml`, `MANIFEST.in`.
✅ GOOD: `src/` layout
```
my_package/
├── src/
│ └── my_package/
│ ├── __init__.py
│ └── module.py
├── pyproject.toml
├── README.md
└── tests/
```
- **Module Organization:**
- Group related functions and classes within a module.
- Keep modules focused on a specific responsibility.
- Use clear and descriptive module names.
- Utilize subpackages for logical grouping of modules within larger projects.
## 2. Declarative Configuration in `pyproject.toml`
- **Component Architecture:**
- Favor modular design, breaking down the project into reusable components.
- Define clear interfaces between components.
- Follow the Single Responsibility Principle (SRP) for each component.
- Consider using a layered architecture if appropriate for your project's complexity.
Configure all project metadata and build settings declaratively in `pyproject.toml`. This aligns with PEP 517/518, enables isolated builds, and makes your package metadata machine-readable without executing code. Avoid `setup.py` for metadata.
- **Code Splitting Strategies:**
- Split large modules into smaller, more manageable files.
- Decompose complex functions into smaller, well-defined functions.
- Extract reusable code into separate modules or packages.
- Employ lazy loading for modules that are not immediately needed.
**Always include `[build-system]` and `[project]` tables.**
## 2. Common Patterns and Anti-patterns:
```toml title="pyproject.toml"
[build-system]
requires = ["setuptools>=61", "setuptools-scm>=8"]
build-backend = "setuptools.build_meta"
- **Design Patterns:**
- **Factory Pattern:** Use factory functions or classes to create instances of objects, especially when complex initialization is required.
- **Dependency Injection:** Inject dependencies into classes or functions to improve testability and reduce coupling.
- **Facade Pattern:** Provide a simplified interface to a complex subsystem.
- **Singleton Pattern:** Use sparingly; ensure thread safety if needed.
- **Observer Pattern:** Useful for event handling and asynchronous operations.
[project]
name = "my-awesome-package"
dynamic = ["version"] # Managed by setuptools-scm
description = "A short description of my awesome package."
readme = "README.md"
requires-python = ">=3.8"
license = { file = "LICENSE" }
authors = [
{ name = "Your Name", email = "your.email@example.com" },
]
keywords = ["python", "utility", "example"]
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
- **Recommended Approaches:**
- **Declaring Dependencies:** Use `install_requires` in `setup.py` or `pyproject.toml` (preferred) to specify project dependencies.
- **Managing Package Data:** Use `package_data` in `setup.py` to include non-code files (e.g., data files, templates) within your package.
- **Creating Entry Points:** Define console scripts using `entry_points` in `setup.py` or `pyproject.toml` to create command-line tools.
- **Versioning:** Follow Semantic Versioning (SemVer) to clearly communicate the nature of changes in each release.
- **Using `pyproject.toml`:** Utilize `pyproject.toml` for build system configuration, build dependencies and other metadata. This aligns with modern packaging practices.
[project.urls]
Homepage = "https://github.com/yourusername/my-awesome-package"
Documentation = "https://my-awesome-package.readthedocs.io/"
Repository = "https://github.com/yourusername/my-awesome-package"
- **Anti-patterns and Code Smells:**
- **Large `setup.py` Files:** Keep `setup.py` concise; move complex logic to separate modules.
- **Hardcoded Paths:** Avoid hardcoding file paths; use relative paths or the `pkg_resources` module to access package data.
- **Global State:** Minimize the use of global variables; prefer passing state as arguments to functions or methods.
- **Ignoring Errors:** Always handle exceptions appropriately; never ignore errors without logging or taking corrective action.
- **Over-engineering:** Avoid unnecessary complexity; keep the design simple and focused.
[tool.setuptools]
package-dir = {"" = "src"} # Essential for src/ layout
- **State Management:**
- For CLI tools, use configuration files or environment variables to store persistent state.
- For more complex applications, consider using a database or other persistent storage mechanism.
- Avoid storing sensitive information in plain text configuration files; use encryption or secure storage.
[tool.setuptools_scm]
write_to = "src/my_package/_version.py" # Optional: writes version to a file
```
- **Error Handling:**
- Use `try...except` blocks to handle exceptions gracefully.
- Log errors with sufficient context for debugging.
- Raise custom exceptions to provide more specific error information.
- Avoid catching generic exceptions (`except Exception:`) unless you re-raise them or log the error.
## 3. Version Management with `setuptools-scm`
## 3. Performance Considerations:
Derive your package version directly from VCS (Git) tags using `setuptools-scm`. This eliminates manual version bumps and ensures your package version always reflects your repository state.
- **Optimization Techniques:**
- **Code Profiling:** Use profiling tools (e.g., `cProfile`) to identify performance bottlenecks.
- **Algorithm Optimization:** Choose efficient algorithms and data structures.
- **Caching:** Implement caching mechanisms to reduce redundant computations.
- **Code Optimization:** Use efficient code constructs and avoid unnecessary operations.
- **Concurrency/Parallelism:** Consider using threading or multiprocessing for CPU-bound tasks.
1. **Declare `setuptools-scm`** in `build-system.requires`.
2. **Set `dynamic = ["version"]`** in `[project]`.
3. **Configure `[tool.setuptools_scm]`** (optional, but recommended for `write_to`).
- **Memory Management:**
- Use generators or iterators to process large datasets without loading everything into memory.
- Release resources (e.g., file handles, network connections) promptly.
- Avoid creating unnecessary copies of data.
- Be mindful of memory leaks; use memory profiling tools to detect them.
❌ BAD: Manual version in `pyproject.toml` or `__init__.py`
```toml
# pyproject.toml
[project]
version = "0.1.0" # ❌ BAD: Requires manual updates
```
- **Bundle Size Optimization:**
- Minimize the size of your package by excluding unnecessary files (e.g., test files, documentation) from the distribution.
- Use compression to reduce the size of package data.
- Consider using a smaller version of a dependency or only requiring features of the dependency that you need.
✅ GOOD: Dynamic versioning with `setuptools-scm`
```toml title="pyproject.toml"
[build-system]
requires = ["setuptools>=61", "setuptools-scm>=8"]
build-backend = "setuptools.build_meta"
- **Lazy Loading:**
- Defer loading of modules or data until they are actually needed.
- Use the `importlib` module to dynamically import modules at runtime.
- Implement lazy properties to defer the computation of attribute values.
[project]
name = "my-package"
dynamic = ["version"] # ✅ GOOD: Version derived from Git tags
## 4. Security Best Practices:
[tool.setuptools_scm]
# Optional: write the version to a file for runtime access
write_to = "src/my_package/_version.py"
```
- **Common Vulnerabilities:**
- **Dependency Confusion:** Prevent dependency confusion attacks by using a unique package name and verifying dependencies.
- **Arbitrary Code Execution:** Avoid using `eval()` or `exec()` to execute untrusted code.
- **Injection Attacks:** Sanitize user inputs to prevent injection attacks (e.g., SQL injection, command injection).
- **Cross-Site Scripting (XSS):** Encode output to prevent XSS attacks, particularly when dealing with web interfaces.
## 4. Dependency Declaration
- **Input Validation:**
- Validate all user inputs to ensure they conform to expected formats and ranges.
- Use regular expressions or validation libraries to enforce input constraints.
- Sanitize inputs to remove or escape potentially malicious characters.
Manage all dependencies declaratively in `pyproject.toml`.
- **Authentication and Authorization:**
- Use secure authentication mechanisms (e.g., OAuth 2.0, JWT) to verify user identities.
- Implement authorization checks to ensure that users only have access to the resources they are authorized to access.
- Store passwords securely using hashing algorithms (e.g., bcrypt, scrypt).
* **`dependencies`**: For runtime dependencies.
* **`optional-dependencies`**: For optional dependencies (e.g., `dev`, `test`, `docs`).
- **Data Protection:**
- Encrypt sensitive data at rest and in transit.
- Use HTTPS to secure communication between clients and servers.
- Implement data masking or anonymization techniques to protect personally identifiable information (PII).
❌ BAD: `dependency_links` or `requirements.txt` for runtime dependencies
```toml
# pyproject.toml
[project]
# ❌ BAD: dependency_links is deprecated.
# ❌ BAD: requirements.txt is for application environments, not libraries.
```
- **Secure API Communication:**
- Use API keys or tokens to authenticate API requests.
- Enforce rate limiting to prevent denial-of-service attacks.
- Validate API requests and responses to ensure data integrity.
✅ GOOD: `dependencies` and `optional-dependencies`
```toml title="pyproject.toml"
[project]
dependencies = [ # ✅ GOOD: Runtime dependencies
"requests~=2.30",
"rich>=13.0.0",
]
## 5. Testing Approaches:
[project.optional-dependencies] # ✅ GOOD: Optional dependencies
dev = [
"pytest>=7.0",
"pytest-cov",
"black",
"isort",
"mypy",
"setuptools-scm[toml]>=8", # Include setuptools-scm for dev installs
]
docs = [
"sphinx",
"furo",
]
```
- **Unit Testing:**
- Write unit tests for each module and function to verify their correctness.
- Use mocking or stubbing to isolate units of code from their dependencies.
- Aim for high test coverage to ensure that all code paths are tested.
- Use `pytest` and `unittest` modules.
## 5. Entry Points for Scripts and Plugins
- **Integration Testing:**
- Write integration tests to verify the interactions between different components of the system.
- Test the integration with external dependencies (e.g., databases, APIs).
- Use test doubles or test environments to simulate external dependencies.
Expose console scripts, GUI entry points, or plugin APIs using the `[project.scripts]` and `[project.entry-points]` tables. This is the standard way to create discoverable extensions and command-line tools.
- **End-to-End Testing:**
- Write end-to-end tests to verify the functionality of the entire system from the user's perspective.
- Use browser automation tools (e.g., Selenium, Playwright) to simulate user interactions.
- Test the system in a realistic environment.
```toml title="pyproject.toml"
[project.scripts] # ✅ GOOD: Console scripts
my-cli = "my_package.cli:main"
- **Test Organization:**
- Organize tests into separate directories (e.g., `tests/`).
- Use descriptive test names to clearly indicate what each test is verifying.
- Group related tests into test classes or modules.
- Use test fixtures to set up and tear down test environments.
[project.gui-scripts] # ✅ GOOD: GUI scripts
my-gui = "my_package.gui:start_app"
- **Mocking and Stubbing:**
- Use mocking libraries (e.g., `unittest.mock`, `pytest-mock`) to create mock objects that simulate the behavior of dependencies.
- Use stubbing to replace dependencies with simplified versions that return predefined values.
- Avoid over-mocking; only mock dependencies that are difficult to test directly.
[project.entry-points."my_package.plugins"] # ✅ GOOD: Custom plugin entry points
plugin_a = "my_package.plugins:PluginA"
plugin_b = "my_package.plugins:PluginB"
```
## 6. Common Pitfalls and Gotchas:
## 6. Resource Files and Namespace Packages
- **Frequent Mistakes:**
- **Incorrect Dependency Specifications:** Ensure that dependencies are correctly specified in `install_requires` or `pyproject.toml` with accurate version constraints.
- **Missing Package Data:** Remember to include non-code files in `package_data` if they are required at runtime.
- **Inconsistent Versioning:** Follow Semantic Versioning (SemVer) consistently and update version numbers appropriately.
- **Ignoring Encoding Issues:** Handle text encoding correctly to avoid errors when dealing with non-ASCII characters.
- **Failing to Test:** Write comprehensive tests to catch errors early and prevent regressions.
Bundle non-code assets (e.g., templates, data files) cleanly using `package_data`. For larger projects, use native namespace package support (PEP 420).
- **Edge Cases:**
- **Platform-Specific Issues:** Test your package on different operating systems and Python versions to identify platform-specific issues.
- **Dependency Conflicts:** Be aware of potential dependency conflicts and use virtual environments to isolate your project's dependencies.
- **Unicode Handling:** Handle Unicode characters correctly, especially when dealing with user inputs or file names.
- **Resource Limits:** Be mindful of resource limits (e.g., memory, file handles) when processing large datasets.
```toml title="pyproject.toml"
[tool.setuptools.package-data]
"my_package" = ["data/*.json", "templates/*.html"] # ✅ GOOD: Include specific data files
```
- **Version-Specific Issues:**
- Be aware of compatibility issues between different versions of setuptools.
- Consult the setuptools documentation for version-specific recommendations.
For namespace packages, simply omit `__init__.py` from the parent directory and ensure `setuptools` is configured to find them (e.g., via `package-dir` for `src/` layout).
- **Compatibility Concerns:**
- Test your package with different versions of Python to ensure compatibility.
- Be aware of potential conflicts with other libraries or frameworks.
- Use conditional imports or feature detection to handle compatibility issues gracefully.
```
src/
└── my_namespace/
├── my_package_a/
│ └── __init__.py
└── my_package_b/
└── __init__.py
```
- **Debugging Strategies:**
- Use a debugger to step through your code and inspect variables.
- Add logging statements to track the flow of execution and identify errors.
- Use unit tests to isolate and reproduce bugs.
- Consult online resources (e.g., Stack Overflow) and the setuptools documentation for troubleshooting tips.
## 7. Development Workflow
## 7. Tooling and Environment:
Always use a virtual environment. For local development, install your package in "editable" mode to reflect source changes instantly.
- **Recommended Development Tools:**
- **Virtual Environment Managers:** `venv`, `virtualenv`, `conda` or Poetry to create isolated Python environments.
- **Package Managers:** `pip` or Poetry to install and manage dependencies.
- **Code Editors:** VS Code, PyCharm, Sublime Text, or other IDEs with Python support.
- **Debuggers:** `pdb` or IDE-integrated debuggers.
- **Profilers:** `cProfile` to identify performance bottlenecks.
- **Testing Frameworks:** `pytest` or `unittest` for writing and running tests.
- **Linters and Formatters:** `flake8`, `pylint`, `black`, and `isort` to enforce code style and quality.
- **Build System:** `build` to build distributions.
```bash
# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate # On Unix/macOS
# .venv\Scripts\activate # On Windows
- **Build Configuration:**
- Use `setup.cfg` or `pyproject.toml` to configure the build process.
- Specify dependencies, package data, and entry points in the configuration file.
- Use build scripts to automate build tasks.
# Install your package in editable mode with dev dependencies
pip install -e ".[dev]" # ✅ GOOD: Editable install for live code changes
```
**Pitfall**: Entry points (scripts, plugins) are only discoverable *after* the package is installed (even in editable mode). If you add a new entry point, you might need to re-run `pip install -e .` for it to register.
- **Linting and Formatting:**
- Use `flake8` or `pylint` to enforce code style guidelines.
- Use `black` to automatically format your code.
- Use `isort` to sort imports alphabetically.
## 8. Building and Publishing
- **Deployment:**
- Use `twine` to securely upload your package to PyPI.
- Use virtual environments to isolate your application's dependencies in production.
- Consider using containerization (e.g., Docker) to create reproducible deployment environments.
Generate standard distribution packages (wheels and source distributions) using `build`, and upload them securely with `twine`.
- **CI/CD:**
- Use CI/CD systems (e.g., GitHub Actions, Jenkins, Travis CI, CircleCI) to automate building, testing, and deploying your package.
- Configure CI/CD pipelines to run tests, linters, and formatters on every commit.
- Automate the release process using CI/CD.
```bash
# Ensure build and twine are installed in your dev environment
pip install build twine
By adhering to these best practices, you can effectively leverage `setuptools` to create well-structured, maintainable, and high-quality Python packages.
# Clean any previous builds
rm -rf dist/ build/ *.egg-info/
# Build distributions
python -m build # ✅ GOOD: Creates .whl and .tar.gz in dist/
# Upload to TestPyPI (always test here first!)
twine upload --repository testpypi dist/* # ✅ GOOD: Secure upload
# Upload to PyPI
twine upload dist/*
```
## 9. Type Hints
While not `setuptools`-specific, consistently apply type hints throughout your Python codebase. This improves code readability, maintainability, and enables static analysis tools to catch errors early. `setuptools` itself does not dictate type hint usage, but a well-packaged project is a well-typed project.
```python
# ✅ GOOD: Use type hints for clarity and static analysis
def calculate_sum(a: int, b: int) -> int:
return a + b
```
## 10. Custom Build Logic (When Absolutely Necessary)
If you *must* perform custom build steps (e.g., compiling C extensions, generating code), `setup.py` is still the place for imperative logic. However, keep it minimal and ensure it only handles build-time operations, not metadata.
```python title="setup.py"
# ❌ BAD: Defining metadata here. Use pyproject.toml instead.
# from setuptools import setup
# setup(name='my_package', version='0.1.0', ...)
# ✅ GOOD: Minimal setup.py for custom build logic (e.g., C extensions)
from setuptools import setup, Extension
my_extension = Extension(
'my_package.my_c_module',
sources=['src/my_package/my_c_module.c'],
)
setup(
ext_modules=[my_extension],
)
```
**Note**: Even for extensions, much can be configured in `pyproject.toml` directly with `setuptools`'s `[tool.setuptools.extensions]` table. Only resort to `setup.py` if truly complex, imperative logic is required.