python-type-hints
БесплатноБез исполняемых скриптовНе проверенComplete Python type hints system. PROACTIVELY activate for: (1) Built-in generics (list[str], dict[str, int]), (2) Union types (str | None), (3) Type…
от JosiahSiegel★ 67 звёзд на GitHubОб этом скилле
Quick Reference
| Type | Syntax (3.9+) | Example |
|---|---|---|
| List | list[str] |
names: list[str] = [] |
| Dict | dict[str, int] |
ages: dict[str, int] = {} |
| Optional | str | None |
name: str | None = None |
| Union | int | str |
value: int | str |
| Callable | Callable[[int], str] |
func: Callable[[int], str] |
| Feature | Version | Syntax |
|---|---|---|
| Type params | 3.12+ | def first[T](items: list[T]) -> T: |
| type alias | 3.12+ | type Point = tuple[float, float] |
| Self | 3.11+ | def copy(self) -> Self: |
| TypeIs | 3.13+ | def is_str(x) -> TypeIs[str]: |
| Construct | Use Case |
|---|---|
Protocol |
Structural subtyping (duck typing) |
TypedDict |
Dict with specific keys |
Literal["a", "b"] |
Specific values only |
Final[str] |
Cannot be reassigned |
When to Use This Skill
Use for static type checking:
- Adding type hints to functions and classes
- Creating typed dictionaries with TypedDict
- Defining protocols for duck typing
- Configuring mypy or pyright
- Writing generic functions and classes
Related skills:
- For Python fundamentals: see
python-fundamentals-313 - For testing: see
python-testing - For FastAPI schemas: see
python-fastapi
Python Type Hints Complete Guide
Overview
Type hints enable static type checking, better IDE support, and self-documenting code. Python's typing system is gradual - you can add types incrementally.
Modern Type Hints (Python 3.9+)
Built-in Generic Types
# Python 3.9+ - Use built-in types directly
# No need for typing.List, typing.Dict, etc.
def process_items(items: list[str]) -> dict[str, int]:
return {item: len(item) for item in items}
# Collections
names: list[str] = ["Alice", "Bob"]
ages: dict[str, int] = {"Alice": 30, "Bob": 25}
coordinates: tuple[float, float] = (1.0, 2.0)
unique_ids: set[int] = {1, 2, 3}
frozen_data: frozenset[str] = frozenset(["a", "b"])
# Nested generics
matrix: list[list[int]] = [[1, 2], [3, 4]]
config: dict[str, list[str]] = {"servers": ["a", "b"]}
Union Types (Python 3.10+)
# Old way (still works)
from typing import Union, Optional
def old_style(value: Union[int, str]) -> Optional[str]:
return str(value) if value else None
# New way (Python 3.10+)
def new_style(value: int | str) -> str | None:
return str(value) if value else None
# Optional is just Union with None
# Optional[str] == str | None
Type Aliases
# Simple type alias
UserId = int
Username = str
def get_user(user_id: UserId) -> Username:
return "user_" + str(user_id)
# Complex type alias
from typing import TypeAlias
JsonValue: TypeAlias = str | int | float | bool | None | list["JsonValue"] | dict[str, "JsonValue"]
# Python 3.12+ type statement
type Point = tuple[float, float]
type Vector[T] = list[T]
type JsonDict = dict[str, "JsonValue"]
Type Parameters (Python 3.12+)
# Old way with TypeVar
from typing import TypeVar
T = TypeVar("T")
def first_old(items: list[T]) -> T:
return items[0]
# New way (Python 3.12+)
def first[T](items: list[T]) -> T:
return items[0]
# Generic classes
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T:
return self._items.pop()
# Multiple type parameters
def merge[K, V](d1: dict[K, V], d2: dict[K, V]) -> dict[K, V]:
return {**d1, **d2}
# Bounded type parameters
from typing import SupportsLessThan
def minimum[T: SupportsLessThan](a: T, b: T) -> T:
return a if a < b else b
# Default type parameters (Python 3.13+)
class Container[T = int]:
def __init__(self, value: T) -> None:
self.value = value
Function Signatures
Basic Functions
from typing import Callable, Iterable, Iterator
# Simple function
def greet(name: str) -> str:
return f"Hello, {name}!"
# Multiple parameters
def create_user(name: str, age: int, email: str | None = None) -> dict:
return {"name": name, "age": age, "email": email}
# *args and **kwargs
def log(*args: str, **kwargs: int) -> None:
for arg in args:
print(arg)
for key, value in kwargs.items():
print(f"{key}={value}")
# Callable type
def apply_func(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
# Higher-order functions
def make_multiplier(n: int) -> Callable[[int], int]:
def multiplier(x: int) -> int:
return x * n
return multiplier
Overloads
from typing import overload, Literal
@overload
def process(data: str) -> str: ...
@overload
def process(data: bytes) -> bytes: ...
@overload
def process(data: int) -> int: ...
def process(data: str | bytes | int) -> str | bytes | int:
if isinstance(data, str):
return data.upper()
elif isinstance(data, bytes):
return data.upper()
Установить python-type-hints в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл python-type-hints?
Complete Python type hints system. PROACTIVELY activate for: (1) Built-in generics (list[str], dict[str, int]), (2) Union types (str | None), (3) Type parameter syntax 3.12+, (4) Protocol for structural typing, (5) TypedDict for dict schemas, (6) Literal and Final types, (7) TypeGuard and TypeIs, (8) ParamSpec for decorators, (9) Mypy/Pyright configuration. Provides: Type syntax, Protocol patterns, TypedDict, mypy config. Ensures static type safety with gradual typing strategy.
Как установить скилл python-type-hints?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл python-type-hints запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic