SKILL.md
Quick Reference (30 seconds)
Python 3.13+ Development Specialist - FastAPI, Django, async patterns, pytest, and modern Python features.
Auto-Triggers: Python files with .py extension, pyproject.toml, requirements.txt, pytest.ini, FastAPI or Django discussions
Core Capabilities:
- Python 3.13 Features: JIT compiler via PEP 744, GIL-free mode via PEP 703, pattern matching with match and case statements
- Web Frameworks: FastAPI 0.115 and later, Django 5.2 LTS
- Data Validation: Pydantic v2.9 with model_validate patterns
- ORM: SQLAlchemy 2.0 async patterns
- Testing: pytest with fixtures, async testing, parametrize decorators
- Package Management: poetry, uv, pip with pyproject.toml
- Type Hints: Protocol, TypeVar, ParamSpec, and modern typing patterns
- Async: asyncio, async generators, and task groups
- Data Science: numpy, pandas, and polars basics
Quick Patterns
FastAPI Endpoint Pattern:
Import FastAPI and Depends from fastapi, and BaseModel from pydantic. Create a FastAPI application instance. Define a UserCreate model class inheriting from BaseModel with name and email string fields. Create an async post endpoint at the users path that accepts a UserCreate parameter and returns a User by calling UserService.create with await.
Pydantic v2.9 Validation Pattern:
Import BaseModel and ConfigDict from pydantic. Define a User class inheriting from BaseModel. Set modelconfig using ConfigDict with fromattributes set to True and strstripwhitespace set to True. Add id as integer, name as string, and email as string fields. Use modelvalidate to create from ORM objects and modelvalidate_json to create from JSON data.
pytest Async Test Pattern:
Import pytest and mark the test function with pytest.mark.asyncio decorator. Create an async test function that takes asyncclient as a fixture parameter. Send a post request to the users endpoint with a JSON body containing a name field. Assert that the response statuscode equals 201.
Implementation Guide (5 minutes)
Python 3.13 New Features
JIT Compiler via PEP 744:
- Experimental feature disabled by default
- Enable using the PYTHON_JIT environment variable set to 1
- Build option available as enable-experimental-jit flag
- Provides performance improvements for CPU-bound code
- Uses copy-and-patch JIT that translates specialized bytecode to machine code
GIL-Free Mode via PEP 703:
- Experimental free-threaded build available as python3.13t
- Allows true parallel thread execution
- Available in official Windows and macOS installers
- Best suited for CPU-intensive multi-threaded applications
- Not recommended for production use yet
Pattern Matching with match and case:
Create a process_response function that takes a response dictionary and returns a string. Use match statement on response. For case with status ok and data field, return success message with the data. For case with status error and message field, return error message. For case with status matching pending or processing using a guard condition, return in progress message. For default case using underscore, return unknown response.
FastAPI 0.115+ Patterns
Async Dependency Injection:
Import FastAPI, Depends from fastapi, AsyncSession from sqlalchemy.ext.asyncio, and asynccontextmanager from contextlib. Create a lifespan async context manager decorated with asynccontextmanager that takes the FastAPI app. In the lifespan, call await initdb for startup, yield, then call await cleanup for shutdown. Create the FastAPI app with the lifespan parameter. Define an async getdb function returning AsyncGenerator of AsyncSession that uses async with on asyncsession and yields the session. Create a get endpoint for users with userid path parameter, using Depends with getdb to inject the database session. Call await getuserbyid and return UserResponse.model_validate with the user.
Class-Based Dependencies:
Create a Paginator class with an init method accepting page defaulting to 1 and size defaulting to 20. Set self.page to max of 1 and page, self.size to min of 100 and max of 1 and size, and self.offset to page minus 1 multiplied by size. Create a listitems endpoint using Depends on Paginator to inject pagination and return items using getpage with offset and size.
Django 5.2 LTS Features
Composite Primary Keys:
Create an OrderItem model with ForeignKey to Order with CASCADE deletion, ForeignKey to Product with CASCADE deletion, and an IntegerField for quantity. In the Meta class, set pk to models.CompositePrimaryKey with order and product fields.
URL Reverse with Query Parameters:
Import reverse from django.urls. Call reverse with the search view name, query dictionary containing q set to django and page set to 1, and fragment set to results. The result is the search path with query string and fragment.
Automatic Model Imports in Shell:
Run python manage.py shell and models from all installed apps are automatically imported without explicit import statements.
Pydantic v2.9 Deep Patterns
Reusable Validators with Annotated:
Import Annotated from typing and AfterValidator and BaseModel from pydantic. Define a validatepositive function that takes an integer v and returns an integer. If v is less than or equal to 0, raise ValueError with must be positive message. Otherwise return v. Create PositiveInt as Annotated with int and AfterValidator using validatepositive. Use PositiveInt in model fields for price and quantity.
Model Validator for Cross-Field Validation:
Import BaseModel and modelvalidator from pydantic, and Self from typing. Create a DateRange model with startdate and enddate as date fields. Add a modelvalidator decorator with mode set to after. In the validatedates method returning Self, check if enddate is before start_date and raise ValueError if so, otherwise return self.
ConfigDict Best Practices:
Create a BaseSchema model with modelconfig set to ConfigDict. Set fromattributes to True for ORM object support, populatebyname to True to allow aliases, extra to forbid to fail on unknown fields, and strstripwhitespace to True to clean strings.
SQLAlchemy 2.0 Async Patterns
Engine and Session Setup:
Import createasyncengine, asyncsessionmaker, and AsyncSession from sqlalchemy.ext.asyncio. Create engine using createasyncengine with the postgresql+asyncpg connection string, poolpreping set to True, and echo set to True. Create asyncsession using asyncsessionmaker with the engine, class set to AsyncSession, and expireoncommit set to False to prevent detached instance errors.
Repository Pattern:
Create a UserRepository class with an init method taking an AsyncSession. Define an async getbyid method that executes a select query with a where clause for userid, returning scalaroneornone result. Define an async create method that creates a User from UserCreate model_dump, adds to session, commits, refreshes, and returns the user.
Streaming Large Results:
Create an async stream_users function that takes an AsyncSession. Call await db.stream with the select User query. Use async for to iterate over result.scalars and yield each user.
pytest Advanced Patterns
Async Fixtures with pytest-asyncio:
Import pytest, pytestasyncio, and AsyncClient from httpx. Decorate fixtures with pytestasyncio.fixture. Create an asyncclient fixture that uses async with on AsyncClient with app and baseurl, yielding the client. Create a dbsession fixture that uses async with on asyncsession and session.begin, yielding session and calling await session.rollback.
Parametrized Tests:
Use pytest.mark.parametrize decorator with inputdata and expectedstatus parameter names. Provide test cases as tuples with dictionaries and expected status codes. Add ids for valid, emptyname, and missingname cases. The test function takes asyncclient, inputdata, and expectedstatus, posts to users endpoint, and asserts statuscode matches expected.
Fixture Factories:
Create a user_factory fixture that returns an async function. The inner function takes db as AsyncSession and keyword arguments. Set defaults dictionary with name and email. Create User with defaults merged with kwargs using the pipe operator, add to db, commit, and return user.
Type Hints Modern Patterns
Protocol for Structural Typing:
Import Protocol and runtimecheckable from typing. Apply runtimecheckable decorator. Define a Repository Protocol with generic type T. Add abstract async get method taking int id returning T or None, async create method taking dict data returning T, and async delete method taking int id returning bool.
ParamSpec for Decorators:
Import ParamSpec, TypeVar, and Callable from typing, and wraps from functools. Define P as ParamSpec and R as TypeVar. Create a retry decorator function taking times defaulting to 3 that returns a callable wrapper. The inner decorator wraps the function and the wrapper iterates for the specified times, trying to await the function and re-raising on the last attempt.
Package Management
pyproject.toml with Poetry:
In the tool.poetry section, set name, version, and python version constraint. Under dependencies, add fastapi, pydantic, and sqlalchemy with asyncio extra. Under dev dependencies, add pytest, pytest-asyncio, and ruff. Configure ruff with line-length and target-version. Set pytest asynciomode to auto in inioptions.
uv Fast Package Manager:
Install uv using curl with the install script from astral.sh. Create virtual environment with uv venv. Install dependencies with uv pip install from requirements.txt. Add dependencies with uv add command.
Advanced Implementation (10+ minutes)
For comprehensive coverage including:
- Production deployment patterns for Docker and Kubernetes
- Advanced async patterns including task groups and semaphores
- Data science integration with numpy, pandas, and polars
- Performance optimization techniques
- Security best practices following OWASP patterns
- CI/CD integration patterns
See:
- reference.md for complete reference documentation
- examples.md for production-ready code examples
Context7 Library Mappings
- tiangolo/fastapi for FastAPI async web framework
- django/django for Django web framework
- pydantic/pydantic for data validation with type annotations
- sqlalchemy/sqlalchemy for SQL toolkit and ORM
- pytest-dev/pytest for testing framework
- numpy/numpy for numerical computing
- pandas-dev/pandas for data analysis library
- pola-rs/polars for fast DataFrame library
Works Well With
- moai-domain-backend for REST API and microservices architecture
- moai-domain-database for SQL patterns and ORM optimization
- moai-workflow-testing for DDD and testing strategies
- moai-essentials-debug for AI-powered debugging
- moai-foundation-quality for TRUST 5 quality principles
Troubleshooting
Common Issues:
Python Version Check:
Run python with version flag to verify 3.13 or later. Use python with -c flag to print sys.version_info for detailed version information.
Async Session Detached Error:
Set expireoncommit to False in session configuration. Alternatively, use await session.refresh with the object after commit.
pytest asyncio Mode Warning:
In pyproject.toml under tool.pytest.inioptions, set asynciomode to auto and asynciodefaultfixtureloopscope to function.
Pydantic v2 Migration:
The parseobj method is now modelvalidate. The parseraw method is now modelvalidatejson. The fromorm functionality requires from_attributes set to True in ConfigDict.
Last Updated: 2026-01-11 Status: Active (v1.1.0)