Token导航 LogoToken导航TokenDH.com
研究检索权限需确认github未标认证来源可访问clear审计通过

python-type-systemPython type 系统

Agent Skill

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

总安装

441

周安装

18

GitHub Stars

142

下载量

143
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:python-type-system(Python type 系统)
来源仓库:https://github.com/thebushidocollective/han
仓库路径:skills/python-type-system
安装命令:
npx skills add https://github.com/thebushidocollective/han --skill python-type-system
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/thebushidocollective/han --skill python-type-system

简介

用于深入理解 Python 类型系统的原理与设计。

  • 可检索 Mypy、Protocol 或 Structural Typing 相关资料。
  • 适用于高级类型编程与框架开发场景。python-type-system 属于研究检索类 Skill,可作为该场景下的辅助能力补充。
  • 安装方式:通过 GitHub 仓库使用 npx 命令添加。
  • 理论内容较多,建议配合实例练习掌握要点。

SKILL.md

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())

# Works with any matching class
render(Circle())
render(Square())

Protocol with properties and methods:

from typing import Protocol

class Comparable(Protocol):
    def __lt__(self, other: "Comparable") -> bool:
        ...

    def __gt__(self, other: "Comparable") -> bool:
        ...

def find_max(items: list[Comparable]) -> Comparable:
    return max(items)

class Person:
    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age

    def __lt__(self, other: "Person") -> bool:
        return self.age < other.age

    def __gt__(self, other: "Person") -> bool:
        return self.age > other.age

# Works because Person implements Comparable protocol
people = [Person("Alice", 30), Person("Bob", 25)]
oldest = find_max(people)

Runtime checkable protocols:

from typing import Protocol, runtime_checkable

@runtime_checkable
class Serializable(Protocol):
    def to_dict(self) -> dict[str, Any]:
        ...

class User:
    def __init__(self, name: str) -> None:
        self.name = name

    def to_dict(self) -> dict[str, Any]:
        return {"name": self.name}

user = User("Alice")
assert isinstance(user, Serializable)

TypedDict

Define dictionary shapes with TypedDict:

from typing import TypedDict, NotRequired

# Basic TypedDict
class UserDict(TypedDict):
    id: int
    name: str
    email: str

def create_user(user: UserDict) -> UserDict:
    return user

user: UserDict = {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com"
}

# Optional fields (Python 3.11+)
class PersonDict(TypedDict):
    name: str
    age: int
    email: NotRequired[str]  # Optional field

person: PersonDict = {"name": "Bob", "age": 30}

# Total=False makes all fields optional
class ConfigDict(TypedDict, total=False):
    host: str
    port: int
    debug: bool

config: ConfigDict = {"host": "localhost"}

Inheritance with TypedDict:

from typing import TypedDict

class BaseUserDict(TypedDict):
    id: int
    name: str

class ExtendedUserDict(BaseUserDict):
    email: str
    is_active: bool

user: ExtendedUserDict = {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com",
    "is_active": True
}

Literal Types

Restrict values to specific literals:

from typing import Literal

def set_mode(mode: Literal["read", "write", "append"]) -> None:
    print(f"Mode set to {mode}")

# Valid
set_mode("read")

# Type error: not a valid literal
# set_mode("invalid")

# Literal unions
Status = Literal["pending", "active", "completed"]

def update_status(status: Status) -> None:
    print(f"Status: {status}")

# Literal with multiple types
MixedLiteral = Literal[True, 1, "one"]

Type Aliases

Create type aliases for complex types:

from typing import TypeAlias

# Type alias
UserId: TypeAlias = int
UserName: TypeAlias = str

def get_user(user_id: UserId) -> UserName:
    return f"User {user_id}"

# Complex type alias
JsonValue: TypeAlias = (
    dict[str, "JsonValue"]
    | list["JsonValue"]
    | str
    | int
    | float
    | bool
    | None
)

def process_json(data: JsonValue) -> None:
    print(data)

# Generic type alias
Vector: TypeAlias = list[float]
Matrix: TypeAlias = list[Vector]

def multiply_matrix(a: Matrix, b: Matrix) -> Matrix:
    # Implementation
    return [[0.0]]

Callable Types

Type hints for functions and callables:

from typing import Callable

# Function that takes a callback
def apply_operation(
    x: int,
    y: int,
    operation: Callable[[int, int], int]
) -> int:
    return operation(x, y)

def add(a: int, b: int) -> int:
    return a + b

result = apply_operation(5, 3, add)

# Callable with no arguments
def execute(task: Callable[[], None]) -> None:
    task()

# Callback with multiple argument types
Callback: TypeAlias = Callable[[str, int], bool]

def register_handler(callback: Callback) -> None:
    callback("test", 42)

ParamSpec and Concatenate

Advanced callable typing:

from typing import Callable, ParamSpec, TypeVar, Concatenate
from functools import wraps

P = ParamSpec("P")
R = TypeVar("R")

# Decorator that preserves function signature
def log_calls(
    func: Callable[P, R]
) -> Callable[P, R]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_calls
def add(a: int, b: int) -> int:
    return a + b

# Concatenate adds parameters
def with_context(
    func: Callable[Concatenate[str, P], R]
) -> Callable[P, R]:
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        return func("context", *args, **kwargs)
    return wrapper

Type Guards

Create type guards for runtime type narrowing:

from typing import TypeGuard

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

def process_strings(values: list[object]) -> None:
    if is_str_list(values):
        # Type narrowed to list[str]
        for value in values:
            print(value.upper())

# More complex type guard
def is_non_empty_str(val: str | None) -> TypeGuard[str]:
    return val is not None and len(val) > 0

def process_name(name: str | None) -> None:
    if is_non_empty_str(name):
        # Type narrowed to str (non-None)
        print(name.upper())

Overload

Multiple function signatures with overload:

from typing import overload, Literal

@overload
def get_value(key: str, as_int: Literal[True]) -> int:
    ...

@overload
def get_value(key: str, as_int: Literal[False]) -> str:
    ...

def get_value(key: str, as_int: bool) -> int | str:
    value = "42"
    return int(value) if as_int else value

# Type checker knows return type based on literal
int_value: int = get_value("key", True)
str_value: str = get_value("key", False)

Common Patterns

Avoiding common type checking issues:

from typing import TYPE_CHECKING, cast

# Avoid circular imports
if TYPE_CHECKING:
    from my_module import MyClass

def process(obj: "MyClass") -> None:
    pass

# Type casting when you know better than the type checker
def get_data() -> object:
    return {"key": "value"}

data = cast(dict[str, str], get_data())

# Assert type with reveal_type (mypy only)
x = [1, 2, 3]
# reveal_type(x)  # Reveals: list[int]

# Ignore type checking for specific line
result = some_untyped_function()  # type: ignore[no-untyped-call]

# Ignore specific error code
value: Any = get_dynamic_value()
processed = process_value(value)  # type: ignore[arg-type]

When to Use This Skill

Use python-type-system when you need to:

  • Add type hints to Python code for better IDE support and documentation
  • Configure mypy for static type checking in your project
  • Create reusable generic functions and classes
  • Define structural interfaces using Protocol
  • Specify exact dictionary shapes with TypedDict
  • Create type-safe decorators with ParamSpec
  • Implement runtime type narrowing with TypeGuard
  • Handle complex union types and literal types
  • Build type-safe APIs and library interfaces

Best Practices

  • Enable strict mode in mypy for maximum type safety
  • Use Protocol for structural typing instead of ABC when possible
  • Prefer built-in generic types (list, dict) over typing module (3.9+)
  • Use TypedDict for dictionary shapes instead of Dict[str, Any]
  • Create type aliases for complex types to improve readability
  • Use TYPE_CHECKING to avoid circular import issues
  • Add type hints incrementally, starting with public APIs
  • Run mypy in CI/CD to catch type errors early
  • Use reveal_type during development to debug type inference
  • Avoid Any type except when interfacing with untyped code

Common Pitfalls

  • Forgetting to handle None in Optional types
  • Using mutable default arguments (use None and create in function)
  • Not using Protocol for duck-typed interfaces
  • Overusing Any type, reducing type safety benefits
  • Not enabling strict mode in mypy configuration
  • Ignoring type errors instead of fixing them properly
  • Using old typing syntax (List, Dict) in Python 3.9+
  • Circular import issues with forward references
  • Not understanding variance in generic types
  • Mixing runtime behavior with type hints (use TypeGuard)

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenCode

31.64%
按下载量换算45

Codex

22.18%
按下载量换算32

Claude Code

18.54%
按下载量换算27

windsurf

14.01%
按下载量换算20

Antigravity

7.98%
按下载量换算11

Gemini CLI

3.74%
按下载量换算5

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

权限需确认

当前来源未能明确判断权限范围,默认进入异常复核队列。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills