Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Python Typing Patterns

ASecurity

Python type hints and type safety patterns. Triggers on: type hints, typing, TypeVar, Generic, Protocol, mypy, pyright, type annotation, overload, TypedDict.

416 stars
0 votes
0 copies
1 views
Added 2/7/2026
developmentpythonbashsqlfastapiapidatabase

Works with

api

Security Analysis

A100/100

Pro scans all 10 files and shows the line behind each finding

Scanned 2/10/2026

$npx -y skills add aiskillstore/marketplace --skill python-typing-patterns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Python Typing Patterns?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Python Typing Patterns
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/aiskillstore-python-typing-patterns/badge)](https://www.skillsdirectory.com/skills/aiskillstore-python-typing-patterns)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
SKILL.md
---
name: python-typing-patterns
description: "Python type hints and type safety patterns. Triggers on: type hints, typing, TypeVar, Generic, Protocol, mypy, pyright, type annotation, overload, TypedDict."
compatibility: "Python 3.10+ (uses union syntax X | Y). Some patterns require 3.11+ (Self, TypeVarTuple)."
allowed-tools: "Read Write"
depends-on: []
related-skills: [python-pytest-patterns]
---

# Python Typing Patterns

Modern type hints for safe, documented Python code.

## Basic Annotations

```python
# Variables
name: str = "Alice"
count: int = 42
items: list[str] = ["a", "b"]
mapping: dict[str, int] = {"key": 1}

# Function signatures
def greet(name: str, times: int = 1) -> str:
    return f"Hello, {name}!" * times

# None handling
def find(id: int) -> str | None:
    return db.get(id)  # May return None
```

## Collections

```python
from collections.abc import Sequence, Mapping, Iterable

# Use collection ABCs for flexibility
def process(items: Sequence[str]) -> list[str]:
    """Accepts list, tuple, or any sequence."""
    return [item.upper() for item in items]

def lookup(data: Mapping[str, int], key: str) -> int:
    """Accepts dict or any mapping."""
    return data.get(key, 0)

# Nested types
Matrix = list[list[float]]
Config = dict[str, str | int | bool]
```

## Optional and Union

```python
# Modern syntax (3.10+)
def find(id: int) -> User | None:
    pass

def parse(value: str | int | float) -> str:
    pass

# With default None
def fetch(url: str, timeout: float | None = None) -> bytes:
    pass
```

## TypedDict

```python
from typing import TypedDict, Required, NotRequired

class UserDict(TypedDict):
    id: int
    name: str
    email: str | None

class ConfigDict(TypedDict, total=False):  # All optional
    debug: bool
    log_level: str

class APIResponse(TypedDict):
    data: Required[list[dict]]
    error: NotRequired[str]

def process_user(user: UserDict) -> str:
    return user["name"]  # Type-safe key access
```

## Callable

```python
from collections.abc import Callable

# Function type
Handler = Callable[[str, int], bool]

def register(callback: Callable[[str], None]) -> None:
    pass

# With keyword args (use Protocol instead)
from typing import Protocol

class Processor(Protocol):
    def __call__(self, data: str, *, verbose: bool = False) -> int:
        ...
```

## Generics

```python
from typing import TypeVar

T = TypeVar("T")

def first(items: list[T]) -> T | None:
    return items[0] if items else None

# Bounded TypeVar
from typing import SupportsFloat

N = TypeVar("N", bound=SupportsFloat)

def average(values: list[N]) -> float:
    return sum(float(v) for v in values) / len(values)
```

## Protocol (Structural Typing)

```python
from typing import Protocol

class Readable(Protocol):
    def read(self, n: int = -1) -> bytes:
        ...

def load(source: Readable) -> dict:
    """Accepts any object with read() method."""
    data = source.read()
    return json.loads(data)

# Works with file, BytesIO, custom classes
load(open("data.json", "rb"))
load(io.BytesIO(b"{}"))
```

## Type Guards

```python
from typing import TypeGuard

def is_string_list(val: list[object]) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)

def process(items: list[object]) -> None:
    if is_string_list(items):
        # items is now list[str]
        print(", ".join(items))
```

## Literal and Final

```python
from typing import Literal, Final

Mode = Literal["read", "write", "append"]

def open_file(path: str, mode: Mode) -> None:
    pass

# Constants
MAX_SIZE: Final = 1024
API_VERSION: Final[str] = "v2"
```

## Quick Reference

| Type | Use Case |
|------|----------|
| `X \| None` | Optional value |
| `list[T]` | Homogeneous list |
| `dict[K, V]` | Dictionary |
| `Callable[[Args], Ret]` | Function type |
| `TypeVar("T")` | Generic parameter |
| `Protocol` | Structural typing |
| `TypedDict` | Dict with fixed keys |
| `Literal["a", "b"]` | Specific values only |
| `Final` | Cannot be reassigned |

## Type Checker Commands

```bash
# mypy
mypy src/ --strict

# pyright
pyright src/

# In pyproject.toml
[tool.mypy]
strict = true
python_version = "3.11"
```

## Additional Resources

- `./references/generics-advanced.md` - TypeVar, ParamSpec, TypeVarTuple
- `./references/protocols-patterns.md` - Structural typing, runtime protocols
- `./references/type-narrowing.md` - Guards, isinstance, assert
- `./references/mypy-config.md` - mypy/pyright configuration
- `./references/runtime-validation.md` - Pydantic v2, typeguard, beartype
- `./references/overloads.md` - @overload decorator patterns

## Scripts

- `./scripts/check-types.sh` - Run type checkers with common options

## Assets

- `./assets/pyproject-typing.toml` - Recommended mypy/pyright config

---

## See Also

This is a **foundation skill** with no prerequisites.

**Related Skills:**
- `python-pytest-patterns` - Type-safe fixtures and mocking

**Build on this skill:**
- `python-async-patterns` - Async type annotations
- `python-fastapi-patterns` - Pydantic models and validation
- `python-database-patterns` - SQLAlchemy type annotations

Attribution

aiskillstoreaiskillstore
View sourceSee grades on GitHubMore from aiskillstore →
SSkills DirectorySkills Directory

Your tool, in front of Claude Code builders.

3 founder slots · $299/mo · GSC-verified traffic · sponsors can never buy grades.

See placements

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Your tool, in front of Claude Code builders.

3 founder slots · $299/mo · GSC-verified traffic · sponsors can never buy grades.

See placements

Related Skills

Clean Code

Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments

304955 votes

Browser Extension Developer

Use this skill when developing or maintaining browser extension code in the `browser/` directory, including Chrome/Firefox/Edge compatibility, content scripts, background scripts, or i18n updates.

285172 votes

Seo Optimizer

SEO optimization with keyword analysis, readability assessment, technical validation, content quality. Use for search rankings, blog posts, content audits, or encountering keyword density, readability scores, meta tags, schema markup errors.

2222 votes

Google Official Seo Guide

Official Google SEO guide covering search optimization, best practices, Search Console, crawling, indexing, and improving website search visibility based on official Google documentation

1862 votes

Tanstack Start

Build a full-stack TanStack Start app on Cloudflare Workers from scratch — SSR, file-based routing, server functions, D1+Drizzle, better-auth, Tailwind v4+shadcn/ui. Use whenever the user mentions TanStack Start, asks to scaffold a full-stack Cloudflare app with SSR, wants an SSR dashboard, or asks for a React 19 + Cloudflare Workers app with file-based routing and server functions — even if they don't name TanStack Start specifically. No template repo — Claude generates every file fresh per ...

10341 votes
View all in development →