Generate comprehensive Python type hints and typing annotations for code, modules, or projects using the typing module's features.
Generates comprehensive Python type hints and type annotations using the `typing` module, including generics, protocols, TypeVar, type aliases, and other advanced typing features from Python 3.5+.
This skill helps you add complete, accurate type hints to Python code based on the official Python typing module documentation. It handles simple types (int, str, float), generic types (List, Dict, Optional), advanced features (Protocols, TypeVar, NewType), and modern Python 3.12+ syntax (type statement, generic syntax).
When a user requests type hints for Python code, follow these steps:
1. **Analyze the code structure:**
- Identify all functions, methods, and classes that need type annotations
- Determine parameter types from usage patterns, docstrings, or context
- Infer return types from return statements
- Note any complex data structures (nested containers, callbacks, etc.)
2. **Choose appropriate typing constructs:**
- Use simple built-in types where possible: `int`, `str`, `float`, `bool`, `None`
- Use `collections.abc` types (preferred) or `typing` types for containers: `Sequence`, `Mapping`, `Iterable`, `Callable`
- Use union syntax `X | Y` (Python 3.10+) instead of `Union[X, Y]`
- Use `list[T]`, `dict[K, V]` (Python 3.9+) instead of `List[T]`, `Dict[K, V]` when possible
- Use `Optional[T]` or `T | None` for nullable values
- Use `Any` sparingly, only when type is truly dynamic
3. **Apply advanced typing features when needed:**
- **Type aliases**: Use `type` statement (Python 3.12+) or `TypeAlias` for complex repeated types
- **NewType**: Create distinct types for primitive type wrappers (e.g., `UserId = NewType('UserId', int)`)
- **Generics**: Use `TypeVar` or generic syntax `[T]` (Python 3.12+) for generic functions/classes
- **Protocols**: Define structural types with `Protocol` for duck typing
- **Callable**: Annotate function parameters with `Callable[[ArgTypes], ReturnType]`
- **ParamSpec**: Use for higher-order functions that preserve signatures
- **Literal**: Use `Literal['value']` for exact value constraints
- **TypedDict**: Define typed dictionaries with specific keys
4. **Generate annotated code:**
- Add type hints to all function parameters and return values
- Add type annotations to class attributes and instance variables
- Include necessary imports from `typing` or `collections.abc`
- Preserve original code logic and formatting
- Add comments explaining complex type annotations if needed
5. **Ensure compatibility:**
- Ask user for target Python version if not specified
- Use appropriate syntax for the target version (e.g., `list[int]` requires 3.9+, generic syntax `[T]` requires 3.12+)
- Add `from __future__ import annotations` for forward references in older versions if needed
- Suggest modern alternatives for deprecated types (e.g., `Sequence` instead of `typing.List`)
6. **Validate and explain:**
- Check that type hints are consistent and logical
- Highlight any ambiguous cases where multiple type interpretations are possible
- Explain complex type annotations (Protocols, ParamSpec, Concatenate, etc.)
- Suggest running a type checker (mypy, pyright, pytype) to verify annotations
**Input:**
```python
def calculate_area(length, width):
return length * width
```
**Output:**
```python
def calculate_area(length: float, width: float) -> float:
return length * width
```
**Input:**
```python
def first_element(items):
return items[0] if items else None
```
**Output (Python 3.12+):**
```python
from collections.abc import Sequence
def first_element[T](items: Sequence[T]) -> T | None:
return items[0] if items else None
```
**Output (Python 3.9-3.11):**
```python
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar('T')
def first_element(items: Sequence[T]) -> T | None:
return items[0] if items else None
```
**Input:**
```python
def process_servers(servers):
for address, port, options in servers:
connect(address, port, options)
```
**Output (Python 3.12+):**
```python
from collections.abc import Sequence
type ConnectionOptions = dict[str, str]
type Address = tuple[str, int]
type Server = tuple[Address, ConnectionOptions]
def process_servers(servers: Sequence[Server]) -> None:
for address, port, options in servers:
connect(address, port, options)
```
**Input:**
```python
def process_items(data, callback):
results = []
for item in data:
results.append(callback(item, maxlen=100))
return results
```
**Output:**
```python
from collections.abc import Iterable
from typing import Protocol
class Processor(Protocol):
def __call__(self, item: bytes, *, maxlen: int | None = None) -> list[bytes]: ...
def process_items(data: Iterable[bytes], callback: Processor) -> list[list[bytes]]:
results = []
for item in data:
results.append(callback(item, maxlen=100))
return results
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-type-hints-generator/raw