Install the skill above, then run this in your AI tool:
/python-type-safety <your description>
About
Leverage Python's type system to catch errors at static analysis time. Type annotations serve as enforced documentation that tooling validates automatically.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright.
Skill instructions
Python Type Safety
Leverage Python's type system to catch errors at static analysis time. Type annotations serve as enforced documentation that tooling validates automatically.
When to Use This Skill
Adding type hints to existing code
Creating generic, reusable classes
Defining structural interfaces with protocols
Configuring mypy or pyright for strict checking
Understanding type narrowing and guards
Building type-safe APIs and libraries
Core Concepts
1. Type Annotations
Declare expected types for function parameters, return values, and variables.
2. Generics
Write reusable code that preserves type information across different types.
3. Protocols
Define structural interfaces without inheritance (duck typing with type safety).
4. Type Narrowing
Use guards and conditionals to narrow types within code blocks.
Quick Start
python
defget_user(user_id: str) -> User | None:
"""Return type makes 'might not exist' explicit."""
...
# Type checker enforces handling None case
user = get_user("123")
if user isNone:
raise UserNotFoundError("123")
print(user.name) # Type checker knows user is User here
Fundamental Patterns
Pattern 1: Annotate All Public Signatures
Every public function, method, and class should have type annotations.
python
defget_user(user_id: str) -> User:
"""Retrieve user by ID."""
...
defprocess_batch(
items: list[Item],
max_workers: int = 4,
) -> BatchResult[ProcessedItem]:
"""Process items concurrently."""
...
classUserRepository:
def__init__(self, db: Database) -> None:
self._db = db
asyncdeffind_by_id(self, user_id: str) -> User | None:
"""Return User if found, None otherwise."""
...
asyncdeffind_by_email(self, email: str) -> User | None:
...
asyncdefsave(self, user: User) -> User:
"""Save and return user with generated ID."""
...
Use mypy --strict or pyright in CI to catch type errors early. For existing projects, enable strict mode incrementally using per-module overrides.
Use conditionals to narrow types for the type checker.
python
defprocess_user(user_id: str) -> UserData:
user = find_user(user_id)
if user isNone:
raise UserNotFoundError(f"User {user_id} not found")
# Type checker knows user is User here, not User | Nonereturn UserData(
name=user.name,
email=user.email,
)
defprocess_items(items: list[Item | None]) -> list[ProcessedItem]:
# Filter and narrow types
valid_items = [item for item in items if item isnotNone]
# valid_items is now list[Item]return [process(item) for item in valid_items]
Pattern 4: Generic Classes
Create type-safe reusable containers.
python
from typing import TypeVar, Generic
T = TypeVar("T")
E = TypeVar("E", bound=Exception)
classResult(Generic[T, E]):
"""Represents either a success value or an error."""def__init__(
self,
value: T | None = None,
error: E | None = None,
) -> None:
if (value isNone) == (error isNone):
raise ValueError("Exactly one of value or error must be set")
self._value = value
self._error = error
@propertydefis_success(self) -> bool:
returnself._error isNone @propertydefis_failure(self) -> bool:
returnself._error isnotNonedefunwrap(self) -> T:
"""Get value or raise the error."""ifself._error isnotNone:
raiseself._error
returnself._value # type: ignore[return-value]defunwrap_or(self, default: T) -> T:
"""Get value or return default."""ifself._error isnotNone:
return default
returnself._value # type: ignore[return-value]# Usage preserves typesdefparse_config(path: str) -> Result[Config, ConfigError]:
try:
return Result(value=Config.from_file(path))
except ConfigError as e:
return Result(error=e)
result = parse_config("config.yaml")
if result.is_success:
config = result.unwrap() # Type: Config
Detailed worked examples and patterns
Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.
Best Practices Summary
Annotate all public APIs - Functions, methods, class attributes
Use T | None - Modern union syntax over Optional[T]
Run strict type checking - mypy --strict in CI
Use generics - Preserve type info in reusable code
Define protocols - Structural typing for interfaces
Narrow types - Use guards to help the type checker
Bound type vars - Restrict generics to meaningful types
Create type aliases - Meaningful names for complex types
Minimize Any - Use specific types or generics. Any is acceptable for truly dynamic data or when interfacing with untyped third-party code
Document with types - Types are enforceable documentation
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/wshobson/python-type-safety/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@wshobson/python-type-safety@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: Python type safety with type hints, generics, protocols, and strict type checking. Use when adding type annotations, implementing generic classes, defining structural interfaces, or configuring mypy/pyright.
Run aipm add @wshobson/python-type-safety@1.0.0 in a project that has AIPM initialized.
Supported tools
@wshobson/python-type-safety@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.