### Install Python Assistant Plugin Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Commands to install the Python Assistant plugin via the marketplace or from a local source. This setup enables access to the full suite of specialized Python development agents. ```bash # Option 1: From Marketplace (Recommended) /plugin marketplace add pluginagentmarketplace/custom-plugin-python /plugin install python-developer-plugin@pluginagentmarketplace-python # Option 2: Local Installation git clone https://github.com/pluginagentmarketplace/custom-plugin-python.git cd custom-plugin-python /plugin load . ``` -------------------------------- ### Install and Manage Python Packages with Poetry Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/poetry-packaging/SKILL.md Demonstrates the basic commands for installing Poetry, creating a new Python project, adding and installing dependencies, running commands within the project's virtual environment, updating dependencies, viewing the dependency tree, and exporting dependencies to a requirements.txt file. ```bash # Install Poetry curl -sSL https://install.python-poetry.org | python3 - # Create new project poetry new my-awesome-package cd my-awesome-package # Project structure created: # my-awesome-package/ # ├── my_awesome_package/ # │ └── __init__.py # ├── tests/ # │ └── __init__.py # ├── pyproject.toml # └── README.md # Add dependencies poetry add requests poetry add pandas numpy poetry add --group dev pytest black mypy # Install dependencies poetry install # Run commands in virtual environment poetry run python main.py poetry run pytest # Update dependencies poetry update # Show dependency tree poetry show --tree # Export to requirements.txt poetry export -f requirements.txt --output requirements.txt ``` -------------------------------- ### Install Python Assistant Plugin via Marketplace Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/README.md The recommended method for installing the plugin using the Claude Code CLI marketplace commands. This process involves adding the repository, installing the specific plugin package, and restarting the CLI. ```bash # Step 1: Add the marketplace /plugin marketplace add pluginagentmarketplace/custom-plugin-python # Step 2: Install the plugin /plugin install python-developer-plugin@pluginagentmarketplace-python # Step 3: Restart Claude Code ``` -------------------------------- ### Install and Publish Python Package Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/poetry-packaging/SKILL.md Commands to install a package from a test index and publish a package to PyPI using Poetry. ```bash pip install --index-url https://test.pypi.org/simple/ my-awesome-package poetry publish ``` -------------------------------- ### Setup Pytest Testing Environment Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Initializes a testing structure using pytest, including imports for mocking and filesystem handling. This serves as the foundation for writing unit and integration tests for Python projects. ```python import pytest from unittest.mock import Mock, patch from pathlib import Path import tempfile ``` -------------------------------- ### Invoke type-hints skill via CLI Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/type-hints/references/GUIDE.md Demonstrates how to trigger the type-hints skill using the command line interface with a task description. ```bash claude "type-hints - [your task description]" # Example claude "type-hints - analyze the current implementation" ``` -------------------------------- ### Verify Plugin Installation Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/README.md A snippet showing the expected output after a successful installation, listing the available specialized agents provided by the plugin. ```text python-developer-plugin:03-data-science python-developer-plugin:02-web-development python-developer-plugin:06-package-deployment python-developer-plugin:01-python-fundamentals python-developer-plugin:07-best-practices ... and 2 more ``` -------------------------------- ### FastAPI Async Web Framework Example Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/asyncio-programming/SKILL.md Illustrates how to build asynchronous web applications using FastAPI. This example includes defining async routes for handling requests, implementing background tasks for non-blocking operations, and simulating asynchronous database calls. It requires FastAPI and asyncio. ```python from fastapi import FastAPI, BackgroundTasks import asyncio # Placeholder functions for async operations def save_order(order_data): print(f"Saving order: {order_data}") return 123 # Simulate order ID async def fetch_user_from_db(user_id: int): await asyncio.sleep(0.5) # Simulate DB delay return {"id": user_id, "name": "User Name"} async def send_notification(email: str, message: str): await asyncio.sleep(2) # Simulate email sending print(f"Sent email to {email}: {message}") app = FastAPI() # Async route @app.get("/users/{user_id}") async def get_user(user_id: int): # Async database call user = await fetch_user_from_db(user_id) return user @app.post("/orders/") async def create_order(order_data: dict, background_tasks: BackgroundTasks): # Process order synchronously order_id = save_order(order_data) # Send notification in background background_tasks.add_task( send_notification, order_data['customer_email'], f"Order #{order_id} created" ) return {"order_id": order_id} # To run this example: # 1. Save as main.py # 2. Install fastapi uvicorn: pip install fastapi uvicorn # 3. Run: uvicorn main:app --reload ``` -------------------------------- ### Pytest Command-Line Usage Examples Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pytest-testing/SKILL.md Common command-line invocations for pytest, demonstrating how to run all tests, include coverage, generate reports, target specific files or markers, and control test execution behavior. ```bash # Run all tests pytest # Run with coverage pytest --cov=myapp # Generate HTML coverage report pytest --cov=myapp --cov-report=html # Run specific test file pytest tests/test_api.py # Run tests with marker pytest -m slow # Run tests with verbose output pytest -v # Stop on first failure pytest -x ``` -------------------------------- ### Implement type-hints function in Python Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/type-hints/references/GUIDE.md A standard implementation pattern for the type-hints skill in Python, including input validation and docstring documentation. ```python def implement_type_hints(input_data): """ Implement type-hints functionality. Args: input_data: Input to process Returns: Processed result """ # Validate input if not input_data: raise ValueError("Input required") # Process result = process(input_data) # Return return result ``` -------------------------------- ### Advanced pyproject.toml Configuration Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/poetry-packaging/SKILL.md An example of an advanced pyproject.toml file using Poetry, demonstrating configurations for package metadata, file inclusion/exclusion, optional dependencies, dependency groups, platform-specific dependencies, and plugin definitions. ```toml # Advanced pyproject.toml configuration [tool.poetry] name = "advanced-package" version = "1.0.0" description = "Advanced packaging example" # Include/exclude files include = ["my_package/data/*.json"] exclude = ["my_package/tests/*"] [tool.poetry.dependencies] python = "^3.9" # Optional dependencies (extras) psycopg2 = { version = "^2.9", optional = true } mysqlclient = { version = "^2.1", optional = true } [tool.poetry.extras] postgresql = ["psycopg2"] mysql = ["mysqlclient"] all = ["psycopg2", "mysqlclient"] # Multiple dependency groups [tool.poetry.group.test.dependencies] pytest = "^7.0.0" pytest-cov = "^4.0.0" [tool.poetry.group.docs.dependencies] sphinx = "^5.0.0" "sphinx-rtd-theme" = "^1.0.0" [tool.poetry.group.lint.dependencies] black = "^23.0.0" ruff = "^0.1.0" mypy = "^1.0.0" # Platform-specific dependencies [tool.poetry.dependencies.pywin32] version = "^305" platform = "win32" # Plugins [tool.poetry.plugins."my_package.plugins"] plugin1 = "my_package.plugins:plugin1" ``` -------------------------------- ### Install Python Assistant Plugin Locally Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/README.md An alternative installation method for developers who wish to load the plugin directly from a local clone of the repository. Requires cloning the source code and using the local load command. ```bash # Clone the repository git clone https://github.com/pluginagentmarketplace/custom-plugin-python.git cd custom-plugin-python # Load locally /plugin load . # Restart Claude Code ``` -------------------------------- ### Manage Test Fixtures and Setup with conftest.py Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pytest-testing/SKILL.md Shows how to define shared fixtures with varying scopes (function vs module) and perform setup/teardown operations for data and resources. ```python # conftest.py import pytest import tempfile from pathlib import Path @pytest.fixture def sample_data(): """Provide sample data for tests""" return { 'users': [ {'id': 1, 'name': 'Alice', 'email': 'alice@example.com'}, {'id': 2, 'name': 'Bob', 'email': 'bob@example.com'}, ] } @pytest.fixture def temp_file(): """Create temporary file for testing""" with tempfile.NamedTemporaryFile(mode='w', delete=False) as f: f.write("Test data") temp_path = f.name yield temp_path # Cleanup Path(temp_path).unlink() @pytest.fixture(scope='module') def database_connection(): """Module-scoped database connection""" db = DatabaseConnection('test.db') db.connect() yield db db.close() # test_users.py def test_user_count(sample_data): assert len(sample_data['users']) == 2 def test_user_names(sample_data): names = [user['name'] for user in sample_data['users']] assert 'Alice' in names assert 'Bob' in names def test_file_operations(temp_file): content = Path(temp_file).read_text() assert content == "Test data" ``` -------------------------------- ### Multi-stage Dockerfile for Python Application Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt A Dockerfile demonstrating a multi-stage build for a Python application. It uses an initial stage to install dependencies with `uv` for speed, then copies the virtual environment and application code to a clean, slim final image, optimizing for size and security. ```dockerfile # Multi-stage production Dockerfile FROM python:3.12-slim AS builder WORKDIR /app # Install uv for faster builds COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv # Copy dependency files COPY pyproject.toml uv.lock ./ # Install dependencies RUN uv sync --frozen --no-dev --no-editable # Production stage FROM python:3.12-slim WORKDIR /app # Copy virtual environment from builder COPY --from=builder /app/.venv /app/.venv # Copy application COPY src/ ./src/ ``` -------------------------------- ### Running Asynchronous Code in Python Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Shows how to run an asynchronous function, such as `fetch_all_urls` (assumed to be defined elsewhere), using `asyncio.run()`. This is the standard way to start an asyncio event loop and execute the top-level async entry point of an application. ```python import asyncio # Assuming fetch_all_urls is defined elsewhere # async def fetch_all_urls(urls: list[str]) -> dict: # pass if __name__ == '__main__': urls = ['https://api.example.com/data/1', 'https://api.example.com/data/2'] # results = asyncio.run(fetch_all_urls(urls)) # CPU-bound parallel processing example usage: # data = np.random.rand(10_000_000) # result = parallel_compute(data, multiplier=2.0) pass # Placeholder for actual async execution ``` -------------------------------- ### Python Package Structure Example Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Illustrates a typical directory structure for a Python package managed by Poetry, including source code, tests, and configuration files. The `src/` layout is a common convention for better separation of package code. ```text # Package structure # mypackage/ # └─ pyproject.toml # └─ README.md # └─ LICENSE # └─ src/ # │ └─ mypackage/ # │ │ └─ __init__.py # │ │ └─ py.typed # PEP 561 marker # │ │ └─ core.py # │ │ └─ cli.py # │ │ └─ utils.py # └─ tests/ # └─ conftest.py # └─ test_core.py ``` -------------------------------- ### aiohttp Async Web Server and WebSocket Example Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/asyncio-programming/SKILL.md Demonstrates building an asynchronous web server and handling WebSocket connections using the aiohttp library. This includes setting up basic HTTP routes, implementing a WebSocket handler for real-time communication, and performing asynchronous operations within request handlers. Requires aiohttp. ```python from aiohttp import web import asyncio async def handle_request(request): name = request.match_info.get('name', 'Anonymous') await asyncio.sleep(1) # Async operation return web.json_response({'message': f'Hello {name}'}) async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) async for msg in ws: if msg.type == web.WSMsgType.TEXT: await ws.send_str(f"Echo: {msg.data}") elif msg.type == web.WSMsgType.ERROR: print(f'Error: {ws.exception()}') return ws app = web.Application() app.add_routes([ web.get('/', handle_request), web.get('/{name}', handle_request), web.get('/ws', websocket_handler) ]) if __name__ == '__main__': # To run this example: # 1. Save as server.py # 2. Install aiohttp: pip install aiohttp # 3. Run: python server.py # Then access http://localhost:8080/ and ws://localhost:8080/ws web.run_app(app) ``` -------------------------------- ### Implement Modern Python 3.12+ Syntax Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Examples of modern Python features including structural pattern matching, immutable dataclasses with slots, and type-safe protocols. These patterns are recommended for production-grade, memory-efficient code. ```python from dataclasses import dataclass, field from typing import Protocol, Self # Pattern matching (Python 3.10+) def process_command(command: str) -> str: match command: case "start": return "Starting application..." case "stop": return "Stopping application..." case _: return f"Unknown command: {command}" # Modern dataclass with slots for memory efficiency @dataclass(frozen=True, slots=True) class User: name: str email: str roles: tuple[str, ...] = field(default_factory=tuple) def with_role(self, role: str) -> Self: return User(name=self.name, email=self.email, roles=(*self.roles, role)) # Protocol for structural typing class Repository(Protocol): def save(self, entity: object) -> None: ... def find(self, id: str) -> object | None: ... ``` -------------------------------- ### Profile and Benchmark Python Code Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/python-performance/SKILL.md Demonstrates how to use the timeit module for micro-benchmarks, cProfile for function-level analysis, and memory_profiler for tracking memory consumption. These tools help identify performance bottlenecks and memory-intensive operations in Python scripts. ```python import timeit import cProfile import pstats from memory_profiler import profile def list_comprehension(): return [x**2 for x in range(1000)] def map_function(): return list(map(lambda x: x**2, range(1000))) # Micro-benchmark time_lc = timeit.timeit(list_comprehension, number=10000) print(f"List comprehension: {time_lc:.4f}s") # Function profiling def process_data(): return sum([i**2 for i in range(100000)]) profiler = cProfile.Profile() profiler.enable() process_data() profiler.disable() stats = pstats.Stats(profiler).sort_stats('cumulative') stats.print_stats(10) # Memory profiling @profile def memory_intensive(): large_list = [i for i in range(1000000)] return len(large_list) ``` -------------------------------- ### Python Async I/O with aiohttp, aiofiles, and asyncpg Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/asyncio-programming/SKILL.md Demonstrates asynchronous I/O operations in Python using popular libraries. Includes examples for making non-blocking HTTP requests with `aiohttp`, performing asynchronous file read/write operations with `aiofiles`, and connecting to a PostgreSQL database asynchronously with `asyncpg`. ```python import asyncio import aiohttp import aiofiles from typing import List # Async HTTP requests async def fetch_url(session, url): async with session.get(url) as response: return await response.text() async def fetch_multiple_urls(urls: List[str]): async with aiohttp.ClientSession() as session: tasks = [fetch_url(session, url) for url in urls] results = await asyncio.gather(*tasks) return results # Async file operations async def read_file_async(filepath): async with aiofiles.open(filepath, 'r') as f: content = await f.read() return content async def write_file_async(filepath, content): async with aiofiles.open(filepath, 'w') as f: await f.write(content) # Async database operations (example with asyncpg) import asyncpg async def fetch_users(): conn = await asyncpg.connect( user='user', password='password', database='mydb', host='localhost' ) try: rows = await conn.fetch('SELECT * FROM users') return rows finally: await conn.close() ``` -------------------------------- ### Python Object-Oriented Programming with Dataclasses and Protocols Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/agents/01-python-fundamentals.md Provides examples of Object-Oriented Programming in Python, utilizing `dataclasses` for concise class definitions and `Protocol` for defining structural interfaces, along with abstract base classes. ```python from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Protocol @dataclass class User: name: str email: str roles: list[str] = field(default_factory=list) class Repository(Protocol): def save(self, entity: object) -> None: ... def find(self, id: str) -> object | None: ... ``` -------------------------------- ### Python Debugging Checklist and Commands Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/agents/01-python-fundamentals.md Provides a checklist for debugging Python applications, including commands to verify Python version, active virtual environment, installed dependencies, syntax validity, type errors, and import paths. This helps in systematically identifying and resolving issues. ```bash □ 1. Python version correct? → python --version □ 2. Virtual environment active? → which python (Unix) / where python (Win) □ 3. Dependencies installed? → pip list | grep □ 4. Syntax valid? → python -m py_compile file.py □ 5. Type errors? → mypy file.py □ 6. Import paths correct? → python -c "import sys; print(sys.path)" ``` -------------------------------- ### Structure Python Packages and Manage Publishing Workflow Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/poetry-packaging/SKILL.md Provides a recommended directory structure for a Python package, including example `__init__.py` content with versioning and author information. It also outlines the steps for updating the package version using Poetry commands and building distributable artifacts (sdist and wheel) for publishing to PyPI or TestPyPI. ```python # Recommended package structure my-awesome-package/ ├── my_awesome_package/ │ ├── __init__.py # Package initialization │ ├── core.py # Core functionality │ ├── utils.py # Utility functions │ ├── cli.py # Command-line interface │ └── py.typed # Type hints marker ├── tests/ │ ├── __init__.py │ ├── test_core.py │ └── test_utils.py ├── docs/ │ ├── index.md │ └── api.md ├── examples/ │ └── basic_usage.py ├── pyproject.toml ├── README.md ├── LICENSE ├── CHANGELOG.md └── .gitignore # my_awesome_package/__init__.py """ My Awesome Package A comprehensive package for doing awesome things. """ __version__ = "0.1.0" __author__ = "Your Name" __email__ = "you@example.com" from .core import main_function from .utils import helper_function __all__ = ["main_function", "helper_function"] # Publishing workflow # 1. Update version in pyproject.toml poetry version patch # 0.1.0 -> 0.1.1 poetry version minor # 0.1.1 -> 0.2.0 poetry version major # 0.2.0 -> 1.0.0 # 2. Build package poetry build # Creates dist/my_awesome_package-0.1.0.tar.gz # Creates dist/my_awesome_package-0.1.0-py3-none-any.whl # 3. Publish to TestPyPI first poetry config repositories.testpypi https://test.pypi.org/legacy/ poetry publish -r testpypi ``` -------------------------------- ### Build CLI Applications with Typer and Rich Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Demonstrates how to create a production-ready CLI tool with subcommands, arguments, options, and rich terminal output. It utilizes Typer for command routing and Rich for progress bars, tables, and formatted console feedback. ```python import typer from rich.console import Console from rich.table import Table from rich.progress import track from pathlib import Path import json app = typer.Typer(help="MyApp CLI - Production automation tool") console = Console() @app.command() def deploy( environment: str = typer.Argument(..., help="Target environment (dev/staging/prod)"), version: str = typer.Option("latest", "--version", "-v", help="Version to deploy"), dry_run: bool = typer.Option(False, "--dry-run", help="Simulate deployment"), ): """Deploy application to specified environment.""" if dry_run: console.print(f"[yellow]DRY RUN:[/] Would deploy {version} to {environment}") return with console.status(f"Deploying {version} to {environment}..."): pass console.print(f"[green]✓[/] Successfully deployed {version} to {environment}") @app.command() def status( format: str = typer.Option("table", "--format", "-f", help="Output format (table/json)"), ): """Show deployment status across all environments.""" data = [ {"env": "production", "version": "2.1.0", "status": "healthy"}, {"env": "staging", "version": "2.2.0-rc1", "status": "healthy"}, {"env": "development", "version": "2.2.0-dev", "status": "degraded"}, ] if format == "json": console.print_json(json.dumps(data)) return table = Table(title="Deployment Status") table.add_column("Environment", style="cyan") table.add_column("Version", style="magenta") table.add_column("Status") for item in data: status_style = "green" if item["status"] == "healthy" else "red" table.add_row(item["env"], item["version"], f"[{status_style}]{item['status']}") console.print(table) @app.command() def migrate( path: Path = typer.Argument(..., help="Migration files path"), apply: bool = typer.Option(False, "--apply", help="Apply migrations"), ): """Run database migrations.""" migrations = list(path.glob("*.sql")) if not migrations: console.print("[yellow]No migrations found[/]") raise typer.Exit(1) for migration in track(migrations, description="Processing migrations..."): console.print(f" → {migration.name}") if apply: pass console.print(f"[green]✓[/] Processed {len(migrations)} migrations") if __name__ == "__main__": app() ``` -------------------------------- ### Create and Manipulate Pandas DataFrames Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pandas-data-analysis/SKILL.md Demonstrates how to initialize a DataFrame from a dictionary, perform conditional filtering, and add calculated columns based on existing data. ```python import pandas as pd import numpy as np # Create DataFrame data = { 'name': ['Alice', 'Bob', 'Charlie', 'David'], 'age': [25, 30, 35, 28], 'salary': [50000, 60000, 75000, 55000], 'department': ['IT', 'HR', 'IT', 'Sales'] } df = pd.DataFrame(data) # Indexing and filtering it_employees = df[df['department'] == 'IT'] high_earners = df.loc[df['salary'] > 55000, ['name', 'salary']] # Adding calculated columns df['annual_bonus'] = df['salary'] * 0.10 df['age_group'] = pd.cut(df['age'], bins=[0, 30, 40, 100], labels=['Young', 'Mid', 'Senior']) print(df) ``` -------------------------------- ### Django Authentication and Authorization Views Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/django-framework/SKILL.md Provides examples of Django views for user login, logout, and accessing protected resources using decorators like @login_required and @permission_required. ```python # views.py from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import redirect, render def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') return render(request, 'login.html') @login_required def dashboard(request): return render(request, 'dashboard.html') @permission_required('products.add_product') def add_product(request): # Only users with 'add_product' permission can access return render(request, 'products/add.html') ``` -------------------------------- ### Automate CI/CD Pipeline with GitHub Actions Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Automates testing, linting, type checking, and building Docker images. It uses the 'uv' package manager for efficient dependency handling and ensures code quality before deployment. ```yaml name: CI/CD Pipeline on: push: branches: [main, develop] pull_request: branches: [main] env: PYTHON_VERSION: "3.12" jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.11", "3.12"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Install uv uses: astral-sh/setup-uv@v4 - name: Install dependencies run: uv sync --frozen - name: Run linting run: uv run ruff check . - name: Run type checking run: uv run mypy src/ - name: Run tests run: uv run pytest --cov=src --cov-report=xml --cov-fail-under=80 - name: Upload coverage uses: codecov/codecov-action@v4 with: file: coverage.xml build: needs: test runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' steps: - uses: actions/checkout@v4 - name: Build Docker image run: docker build -t myapp:${{ github.sha }} . - name: Push to registry run: | echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin docker push myapp:${{ github.sha }} ``` -------------------------------- ### Invoke Machine Learning Skill (Bash) Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/machine-learning/references/GUIDE.md Demonstrates how to invoke the machine-learning skill using the 'claude' command-line interface. This requires the plugin to be installed and configured. ```bash # Invoke the skill claude "machine-learning - [your task description]" # Example claude "machine-learning - analyze the current implementation" ``` -------------------------------- ### Invoke Debugging Skill (Bash) Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/debugging/references/GUIDE.md Demonstrates how to invoke the debugging skill using the 'claude' command with a task description. This is the basic entry point for using the skill. ```bash # Invoke the skill claude "debugging - [your task description]" # Example claude "debugging - analyze the current implementation" ``` -------------------------------- ### Basic Async HTTP Client with aiohttp (Python) Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Implements a basic asynchronous HTTP client using aiohttp. Includes functions to fetch a single URL with error handling and to concurrently fetch multiple URLs. ```python import asyncio import aiohttp async def fetch_url(session: aiohttp.ClientSession, url: str) -> dict: """Fetch URL with error handling.""" async with session.get(url) as response: response.raise_for_status() return await response.json() async def fetch_all_urls(urls: list[str]) -> list[dict]: """Fetch multiple URLs concurrently.""" async with aiohttp.ClientSession() as session: tasks = [fetch_url(session, url) for url in urls] return await asyncio.gather(*tasks, return_exceptions=True) ``` -------------------------------- ### Visualize Data with Matplotlib and Seaborn Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pandas-data-analysis/SKILL.md Demonstrates creating common statistical plots including line charts for trends, bar charts for categorical comparisons, and histograms for distribution analysis. ```python import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Set style sns.set_style('whitegrid') # Load data df = pd.read_csv('sales_data.csv') # 1. Line plot - Sales trend over time df.groupby('month')['sales'].sum().plot(kind='line', figsize=(10, 6)) plt.title('Monthly Sales Trend') plt.xlabel('Month') plt.ylabel('Total Sales ($)') plt.show() # 2. Bar plot - Sales by category category_sales = df.groupby('category')['sales'].sum().sort_values(ascending=False) category_sales.plot(kind='bar', figsize=(10, 6)) plt.title('Sales by Category') plt.xlabel('Category') plt.ylabel('Total Sales ($)') plt.xticks(rotation=45) plt.show() # 3. Histogram - Price distribution df['price'].hist(bins=30, figsize=(10, 6)) plt.title('Price Distribution') plt.xlabel('Price ($)') plt.ylabel('Frequency') plt.show() ``` -------------------------------- ### Execute Aggregation and Grouping Operations Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pandas-data-analysis/SKILL.md Shows how to perform complex data aggregations, create pivot tables, and use window functions like rolling averages and cumulative sums. ```python import pandas as pd # Sample sales data df = pd.read_csv('sales.csv') # GroupBy aggregation dept_stats = df.groupby('department').agg({ 'salary': ['mean', 'min', 'max'], 'employee_id': 'count' }) # Multiple groupby sales_by_region_product = df.groupby(['region', 'product_category'])['sales'].sum() # Pivot table pivot = df.pivot_table( values='sales', index='product_category', columns='quarter', aggfunc='sum', fill_value=0 ) # Rolling window (moving average) df['sales_ma_7d'] = df.groupby('product_id')['sales'].transform( lambda x: x.rolling(window=7, min_periods=1).mean() ) # Cumulative sum df['cumulative_sales'] = df.groupby('product_id')['sales'].cumsum() ``` -------------------------------- ### Perform Data Cleaning and Transformation Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pandas-data-analysis/SKILL.md Covers techniques for handling missing values, cleaning string data, parsing dates, removing duplicates, and applying custom transformation functions. ```python import pandas as pd # Load data with missing values df = pd.read_csv('sales_data.csv') # Handle missing values df['price'].fillna(df['price'].median(), inplace=True) df['category'].fillna('Unknown', inplace=True) df.dropna(subset=['customer_id'], inplace=True) # Clean text data df['product_name'] = df['product_name'].str.strip().str.lower() df['product_name'] = df['product_name'].str.replace('[^a-zA-Z0-9 ]', '', regex=True) # Convert dates df['order_date'] = pd.to_datetime(df['order_date']) df['year'] = df['order_date'].dt.year df['month'] = df['order_date'].dt.month # Remove duplicates df.drop_duplicates(subset=['order_id'], keep='first', inplace=True) # Apply custom function def categorize_price(price): if price < 50: return 'Low' elif price < 100: return 'Medium' else: return 'High' df['price_category'] = df['price'].apply(categorize_price) ``` -------------------------------- ### Implement Security Best Practices Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Provides utilities for secure password hashing using PBKDF2 and timing-safe comparisons. Also includes a Pydantic model for robust input validation, enforcing password complexity and email formatting. ```python import secrets import hashlib from typing import Annotated from pydantic import BaseModel, Field, SecretStr, field_validator import re def hash_password(password: str) -> str: """Hash password with random salt using PBKDF2.""" salt = secrets.token_bytes(32) key = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 100_000) return salt.hex() + key.hex() def verify_password(stored: str, provided: str) -> bool: """Verify password with timing-safe comparison.""" salt = bytes.fromhex(stored[:64]) stored_key = bytes.fromhex(stored[64:]) key = hashlib.pbkdf2_hmac("sha256", provided.encode(), salt, 100_000) return secrets.compare_digest(key, stored_key) class UserInput(BaseModel): email: Annotated[str, Field(pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$")] password: SecretStr = Field(min_length=8, max_length=128) username: str = Field(min_length=3, max_length=50, pattern=r"^[a-zA-Z0-9_]+$") @field_validator("password") @classmethod def validate_password_strength(cls, v: SecretStr) -> SecretStr: password = v.get_secret_value() if not re.search(r"[A-Z]", password): raise ValueError("Password must contain uppercase letter") if not re.search(r"[a-z]", password): raise ValueError("Password must contain lowercase letter") if not re.search(r"\d", password): raise ValueError("Password must contain digit") if not re.search(r"[!@#$%^&*]", password): raise ValueError("Password must contain special character") return v ``` -------------------------------- ### CLI Application with Typer (Python) Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/agents/08-python-devops-automation.md A basic example of a command-line interface (CLI) application built using the Typer library in Python. This snippet demonstrates how to define commands and options for a CLI tool. ```python import typer app = typer.Typer() @app.command() def main( name: str = typer.Argument("World", help="The name to greet."), formal: bool = typer.Option(False, "--formal", "-f", help="Use a formal greeting."), ): """Greets NAME, optionally formally.""" if formal: print(f"Hello Mr./Ms. {name}") else: print(f"Hello {name}") if __name__ == "__main__": app() ``` -------------------------------- ### Implement Pytest Basics: Assertions, Exceptions, and Parameterization Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/pytest-testing/SKILL.md Demonstrates fundamental pytest usage including simple assertions, exception handling with pytest.raises, and data-driven testing using the parametrize decorator. ```python # test_calculator.py import pytest def add(a, b): return a + b def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b # Basic test def test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0 assert add(0, 0) == 0 # Test exceptions def test_divide_by_zero(): with pytest.raises(ValueError, match="Cannot divide by zero"): divide(10, 0) # Parametrized test @pytest.mark.parametrize("a,b,expected", [ (10, 2, 5), (20, 4, 5), (100, 10, 10), (-10, 2, -5), ]) def test_divide(a, b, expected): assert divide(a, b) == expected # Test with marker @pytest.mark.slow def test_complex_operation(): # This test takes a long time result = sum(range(1000000)) assert result == 499999500000 ``` -------------------------------- ### Implement Memory-Efficient Classes Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/python-performance/SKILL.md Demonstrates the use of __slots__ in Python classes to reduce memory overhead by preventing the creation of instance __dict__ attributes. This is particularly useful when creating a large number of object instances. ```python import sys class RegularPoint: def __init__(self, x, y): self.x = x self.y = y class SlottedPoint: __slots__ = ['x', 'y'] def __init__(self, x, y): self.x = x self.y = y print(sys.getsizeof(RegularPoint(1, 2))) print(sys.getsizeof(SlottedPoint(1, 2))) ``` -------------------------------- ### Python Standard Library Utilities Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/agents/01-python-fundamentals.md Demonstrates the use of several modules from Python's standard library, including `pathlib` for file system operations, `datetime` for time-related tasks, `functools` for caching, and `contextlib` for creating context managers. These are essential for efficient and robust Python development. ```python from pathlib import Path from datetime import datetime, timedelta from functools import lru_cache, partial from contextlib import contextmanager @lru_cache(maxsize=128) def expensive_operation(n: int) -> int: return sum(range(n)) @contextmanager def timer(): start = datetime.now() yield print(f"Elapsed: {datetime.now() - start}") ``` -------------------------------- ### Basic Debugging Implementation (Python) Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/debugging/references/GUIDE.md Provides a Python function pattern for implementing debugging functionality. It includes input validation, processing, and returning a result. Assumes a 'process' function is defined elsewhere. ```python # Example implementation pattern def implement_debugging(input_data): """ Implement debugging functionality. Args: input_data: Input to process Returns: Processed result """ # Validate input if not input_data: raise ValueError("Input required") # Process result = process(input_data) # Return return result ``` -------------------------------- ### Orchestrate Services with Docker Compose Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Configures a production-ready stack including the application, PostgreSQL, and Redis. It manages service dependencies, health checks, resource limits, and persistent storage volumes. ```yaml services: app: build: context: . dockerfile: Dockerfile ports: - "8000:8000" environment: - DATABASE_URL=postgresql://user:pass@db:5432/mydb - REDIS_URL=redis://redis:6379 - SECRET_KEY=${SECRET_KEY} depends_on: db: condition: service_healthy redis: condition: service_started restart: unless-stopped deploy: resources: limits: cpus: '1' memory: 512M db: image: postgres:16-alpine environment: POSTGRES_USER: user POSTGRES_PASSWORD: pass POSTGRES_DB: mydb volumes: - postgres_data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U user -d mydb"] interval: 5s timeout: 5s retries: 5 redis: image: redis:7-alpine command: redis-server --appendonly yes volumes: - redis_data:/data volumes: postgres_data: redis_data: ``` -------------------------------- ### Poetry Project Configuration (pyproject.toml) Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Defines the metadata, dependencies, development dependencies, and build system configuration for a Python package using Poetry. It specifies project details, Python version compatibility, and tool-specific settings for linters like Ruff and type checkers like MyPy. ```toml [tool.poetry] name = "mypackage" version = "2.0.0" description = "Production-ready Python package" authors = ["Your Name "] readme = "README.md" license = "MIT" packages = [{include = "mypackage", from = "src"}] keywords = ["python", "automation", "cli"] [tool.poetry.dependencies] python = "^3.11" requests = "^2.31.0" pydantic = "^2.0.0" click = "^8.1.0" [tool.poetry.group.dev.dependencies] pytest = "^8.0.0" pytest-cov = "^4.1.0" ruff = "^0.3.0" mypy = "^1.8.0" pre-commit = "^3.6.0" [tool.poetry.scripts] myapp = "mypackage.cli:main" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" [tool.ruff] target-version = "py312" line-length = 88 fix = true [tool.ruff.lint] select = ["E", "W", "F", "I", "B", "C4", "UP", "SIM", "S"] ignore = ["E501"] [tool.mypy] python_version = "3.12" strict = true warn_return_any = true ``` -------------------------------- ### Context Manager for Resource Cleanup in Python Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/python-performance/SKILL.md Defines a `ManagedResource` class that implements the context manager protocol (`__enter__` and `__exit__`). This ensures that resources allocated in `__enter__` are properly cleaned up in `__exit__`, even if errors occur. ```python class ManagedResource: def __enter__(self): self.resource = allocate_resource() return self.resource def __exit__(self, exc_type, exc_val, exc_tb): self.resource.cleanup() return False ``` -------------------------------- ### API Client Unit Tests with Mocking (Python) Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Unit tests for an API client using pytest and unittest.mock. Demonstrates mocking external requests.get calls to simulate successful responses and network errors. ```python import pytest from unittest.mock import patch, Mock import requests # Assume APIClient is defined elsewhere class APIClient: def __init__(self, base_url): self.base_url = base_url def fetch_user(self, user_id): url = f"{self.base_url}/users/{user_id}" response = requests.get(url) response.raise_for_status() # Raise an exception for bad status codes return response.json() class TestAPIClient: @patch('myapp.client.requests.get') def test_fetch_user(self, mock_get): # Setup mock response mock_response = Mock() mock_response.json.return_value = {'id': 1, 'name': 'Alice'} mock_response.raise_for_status = Mock() # Mock the method itself mock_get.return_value = mock_response # Test client = APIClient('https://api.example.com') user = client.fetch_user(1) # Assertions assert user['name'] == 'Alice' mock_get.assert_called_once_with('https://api.example.com/users/1') @patch('myapp.client.requests.get') def test_fetch_user_network_error(self, mock_get): mock_get.side_effect = ConnectionError("Network error") client = APIClient('https://api.example.com') with pytest.raises(ConnectionError): client.fetch_user(1) ``` -------------------------------- ### Multiprocessing for CPU-Bound Tasks in Python Source: https://github.com/pluginagentmarketplace/custom-plugin-python/blob/main/skills/python-performance/SKILL.md Demonstrates parallelizing CPU-bound tasks using Python's `multiprocessing` module and `concurrent.futures.ProcessPoolExecutor`. It shows how to divide work across multiple processes to achieve speedups, especially on multi-core processors. ```python import multiprocessing as mp from concurrent.futures import ProcessPoolExecutor def cpu_intensive_task(n): return sum(i * i for i in range(n)) # Single process result = cpu_intensive_task(10000000) # Multiple processes with ProcessPoolExecutor(max_workers=4) as executor: ranges = [2500000, 2500000, 2500000, 2500000] results = executor.map(cpu_intensive_task, ranges) total = sum(results) # 4x speedup on 4 cores! ``` -------------------------------- ### Perform Data Analysis with Pandas Source: https://context7.com/pluginagentmarketplace/custom-plugin-python/llms.txt Demonstrates a complete data analysis workflow including loading, cleaning, aggregating, and visualizing sales data. It covers techniques like method chaining, rolling window calculations, and generating multi-plot dashboards. ```python import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def clean_dataframe(df: pd.DataFrame) -> pd.DataFrame: df['price'].fillna(df['price'].median(), inplace=True) df['product_name'] = df['product_name'].str.strip().str.lower() return df.drop_duplicates(subset=['order_id']) # Aggregation and Visualization summary = df.groupby('category').agg({'sales': 'sum', 'order_id': 'count'}) sns.heatmap(df[['sales', 'price']].corr(), annot=True) plt.show() ```