Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

python-type-system

БесплатноБез исполняемых скриптовНе проверен

Use when Python's type system including type hints, mypy, Protocol, TypedDict, and Generics. Use when working with Python type annotations.

TheBushidoCollectiveот TheBushidoCollective★ 202 звезды на GitHub

Об этом скилле

Python Type System

Master Python's type system to write type-safe, maintainable code. This skill covers type hints, static type checking with mypy, and advanced typing features.

Type Checking Tools

# Install mypy for static type checking
pip install mypy

# Run mypy on a file or directory
mypy my_module.py
mypy src/

# Run with specific configuration
mypy --config-file mypy.ini src/

# Run with strict mode
mypy --strict src/

# Show type coverage report
mypy --html-report mypy-report src/

mypy Configuration

mypy.ini configuration file:

[mypy]
# Global options
python_version = 3.11
warn_return_any = True
warn_unused_configs = True
disallow_untyped_defs = True
disallow_any_unimported = True
no_implicit_optional = True
warn_redundant_casts = True
warn_unused_ignores = True
warn_no_return = True
check_untyped_defs = True
strict_equality = True

# Per-module options
[mypy-tests.*]
disallow_untyped_defs = False

[mypy-third_party.*]
ignore_missing_imports = True

pyproject.toml configuration:

[tool.mypy]
python_version = "3.11"
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_any_unimported = true
no_implicit_optional = true
warn_redundant_casts = true
warn_unused_ignores = true
warn_no_return = true
check_untyped_defs = true
strict_equality = true

tool.mypy.overrides
module = "tests.*"
disallow_untyped_defs = false

Basic Type Hints

Primitive types and collections:

from typing import List, Dict, Set, Tuple, Optional, Union, Any

# Basic types
def greet(name: str) -> str:
    return f"Hello, {name}"

# Collections
def process_items(items: List[str]) -> Dict[str, int]:
    return {item: len(item) for item in items}

# Optional (can be None)
def find_user(user_id: int) -> Optional[str]:
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)

# Union types (multiple possible types)
def process_value(value: Union[int, str]) -> str:
    return str(value)

# Tuple with fixed types
def get_coordinates() -> Tuple[float, float]:
    return (37.7749, -122.4194)

# Any type (avoid when possible)
def process_data(data: Any) -> None:
    print(data)

Modern Type Syntax (Python 3.10+)

Using PEP 604 union syntax:

# Python 3.10+ union syntax with |
def process_value(value: int | str) -> str:
    return str(value)

# Optional with | None
def find_user(user_id: int) -> str | None:
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)

# Multiple unions
def handle_response(
    response: dict | list | str | None
) -> str:
    if response is None:
        return "No response"
    return str(response)

Built-in generic types (Python 3.9+):

# Use built-in types instead of typing module
def process_items(items: list[str]) -> dict[str, int]:
    return {item: len(item) for item in items}

def get_mapping() -> dict[str, list[int]]:
    return {"numbers": [1, 2, 3]}

def get_unique(items: list[str]) -> set[str]:
    return set(items)

# Nested generics
def group_items(
    items: list[tuple[str, int]]
) -> dict[str, list[int]]:
    result: dict[str, list[int]] = {}
    for key, value in items:
        result.setdefault(key, []).append(value)
    return result

Generic Types

Creating generic functions and classes:

from typing import TypeVar, Generic, Sequence

# Type variable
T = TypeVar("T")

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

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

# Constrained type variable
Number = TypeVar("Number", int, float)

def add(a: Number, b: Number) -> Number:
    return a + b  # type: ignore

# Generic class
class Stack(Generic[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()

    def peek(self) -> T | None:
        return self._items[-1] if self._items else None

# Usage
stack: Stack[int] = Stack()
stack.push(1)
stack.push(2)
value: int = stack.pop()

Bound type variables:

from typing import TypeVar
from collections.abc import Sized

# Type variable with upper bound
TSized = TypeVar("TSized", bound=Sized)

def get_length(obj: TSized) -> int:
    return len(obj)

# Works with any Sized type
get_length("hello")
get_length([1, 2, 3])
get_length({"a": 1})

Protocol (Structural Subtyping)

Define interfaces using Protocol:

from typing import Protocol

# Define a protocol
class Drawable(Protocol):
    def draw(self) -> str:
        ...

# Classes that match the protocol don't need inheritance
class Circle:
    def draw(self) -> str:
        return "Drawing circle"

class Square:
    def draw(self) -> str:
        return "Drawing square"

# Function accepts any type matching the protocol
def render(shape: Drawable) -> None:
    print(shape.draw())

# Wor
Полный SKILL.md на GitHub

Установить python-type-system в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Bash
Read

FAQ

Что делает скилл python-type-system?

Use when Python's type system including type hints, mypy, Protocol, TypedDict, and Generics. Use when working with Python type annotations.

Как установить скилл python-type-system?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл python-type-system запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить python-type-system с