mcpField
P
python-type-hints

python-type-hints

github.com/josiahsiegel开发5976 次安装19 周前更新
代码仓库

关于 python-type-hints

面向 Python 开发者的类型提示参考技能,涵盖现代 typing 语法、常见类型结构,以及 mypy 和 pyright 配置,适用于静态类型检查。

主要功能

  1. 01现代泛型与联合类型语法
  2. 02Protocol 与 TypedDict 模式
  3. 03泛型、类型别名和类型守卫
  4. 04mypy 与 pyright 配置

适用场景

  1. 01为函数和类添加类型注解
  2. 02用 TypedDict 描述字典结构
  3. 03通过 Protocol 定义结构化接口
  4. 04配置静态类型检查

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill python-type-hints

安装后在 Claude Code 中输入/python-type-hints确认已加载。

附带文件references/advanced-typing-patterns.md

详细介绍

快速参考

类型语法(3.9+)示例
列表list[str]names: list[str] = []
字典dict[str, int]ages: dict[str, int] = {}
可选str | Nonename: str | None = None
联合int | strvalue: int | str
可调用对象Callable[[int], str]func: Callable[[int], str]
特性版本语法
类型参数3.12+def first[T](items: list[T]) -> T:
类型别名3.12+type Point = tuple[float, float]
Self3.11+def copy(self) -> Self:
TypeIs3.13+def is_str(x) -> TypeIs[str]:
构造用途
Protocol结构化子类型(鸭子类型)
TypedDict包含特定键的字典
Literal["a", "b"]仅允许特定值
Final[str]不可重新赋值

何时使用此技能

用于静态类型检查:

  • 为函数和类添加类型提示
  • 使用 TypedDict 创建类型化字典
  • 为鸭子类型定义协议
  • 配置 mypy 或 pyright
  • 编写泛型函数和类

相关技能:

  • Python 基础知识:参见 python-fundamentals-313
  • 测试:参见 python-testing
  • FastAPI 架构:参见 python-fastapi

Python 类型提示完整指南

概述

类型提示支持静态类型检查、提供更好的 IDE 支持,并使代码自我说明。Python 的类型系统是渐进式的——你可以逐步添加类型。

现代类型提示(Python 3.9+)

内置泛型类型
# 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"]}
联合类型(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
类型别名
# 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"]
类型参数(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

函数签名

基本函数
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
重载
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()
    else:
        return data * 2

# Overload with Literal
@overload
def fetch(url: str, format: Literal["json"]) -> dict: ...
@overload
def fetch(url: str, format: Literal["text"]) -> str: ...
@overload
def fetch(url: str, format: Literal["bytes"]) -> bytes: ...

def fetch(url: str, format: str) -> dict | str | bytes:
    # Implementation
    ...
用于装饰器的 ParamSpec
from typing import ParamSpec, TypeVar, Callable
from functools import wraps

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

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

# Python 3.12+ syntax
def log_calls_new[**P, R](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

类和协议

类类型标注
from typing import ClassVar, Self

class User:
    # Class variable
    count: ClassVar[int] = 0

    def __init__(self, name: str, age: int) -> None:
        self.name = name
        self.age = age
        User.count += 1

    # Self type for method chaining
    def with_name(self, name: str) -> Self:
        self.name = name
        return self

    def with_age(self, age: int) -> Self:
        self.age = age
        return self

# Usage
user = User("Alice", 30).with_name("Bob").with_age(25)
协议(结构化子类型)
from typing import Protocol, runtime_checkable

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

class Resizable(Protocol):
    def resize(self, width: int, height: int) -> None: ...

# Combining protocols
class DrawableAndResizable(Drawable, Resizable, Protocol):
    pass

# Implementation (no explicit inheritance needed!)
class Circle:
    def draw(self) -> None:
        print("Drawing circle")

class Rectangle:
    def draw(self) -> None:
        print("Drawing rectangle")

    def resize(self, width: int, height: int) -> None:
        print(f"Resizing to {width}x{height}")

# Works because Circle has draw() method
def render(shape: Drawable) -> None:
    shape.draw()

render(Circle())  # OK - Circle satisfies Drawable protocol

# Runtime checkable protocol
@runtime_checkable
class Closeable(Protocol):
    def close(self) -> None: ...

# Can use isinstance
if isinstance(file, Closeable):
    file.close()
TypedDict
from typing import TypedDict, Required, NotRequired

# Basic TypedDict
class Movie(TypedDict):
    title: str
    year: int
    director: str

movie: Movie = {"title": "Inception", "year": 2010, "director": "Nolan"}

# With optional keys
class UserProfile(TypedDict, total=False):
    name: str  # Optional
    email: str  # Optional
    age: int   # Optional

# Mixed required and optional (Python 3.11+)
class Article(TypedDict):
    title: Required[str]
    content: Required[str]
    author: NotRequired[str]
    tags: NotRequired[list[str]]

# Inheritance
class DetailedMovie(Movie):
    rating: float
    genres: list[str]
抽象基类
from abc import ABC, abstractmethod

class Repository[T](ABC):
    @abstractmethod
    def get(self, id: int) -> T | None:
        ...

    @abstractmethod
    def save(self, entity: T) -> T:
        ...

    @abstractmethod
    def delete(self, id: int) -> bool:
        ...

class UserRepository(Repository["User"]):
    def get(self, id: int) -> "User | None":
        return self._db.get(id)

    def save(self, entity: "User") -> "User":
        return self._db.save(entity)

    def delete(self, id: int) -> bool:
        return self._db.delete(id)

高级类型

字面量类型
from typing import Literal

# Restrict to specific values
Mode = Literal["r", "w", "a", "rb", "wb"]

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

open_file("test.txt", "r")   # OK
open_file("test.txt", "x")   # Type error!

# Combining literals
HttpMethod = Literal["GET", "POST", "PUT", "DELETE", "PATCH"]
StatusCode = Literal[200, 201, 400, 401, 403, 404, 500]
Final 和常量
from typing import Final

# Constant that shouldn't be reassigned
MAX_SIZE: Final = 100
API_URL: Final[str] = "https://api.example.com"

# Final class methods
class Base:
    from typing import final

    @final
    def critical_method(self) -> None:
        """Cannot be overridden in subclasses."""
        ...

# Final classes
from typing import final

@final
class Singleton:
    """Cannot be subclassed."""
    _instance: "Singleton | None" = None
类型守卫
from typing import TypeGuard, TypeIs

# TypeGuard (narrows type in if block)
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]
        for item in items:
            print(item.upper())

# TypeIs (Python 3.13+ - stricter than TypeGuard)
def is_int(val: int | str) -> TypeIs[int]:
    return isinstance(val, int)

def handle(value: int | str) -> None:
    if is_int(value):
        # value is int
        print(value + 1)
    else:
        # value is str (properly narrowed)
        print(value.upper())
Annotated
from typing import Annotated
from dataclasses import dataclass

# Metadata for validation/documentation
UserId = Annotated[int, "Unique user identifier"]
Email = Annotated[str, "Valid email address"]
Age = Annotated[int, "Must be >= 0"]

@dataclass
class User:
    id: UserId
    email: Email
    age: Age

# With Pydantic
from pydantic import BaseModel, Field

class UserModel(BaseModel):
    id: Annotated[int, Field(gt=0)]
    email: Annotated[str, Field(pattern=r"^[\w.-]+@[\w.-]+\.\w+$")]
    age: Annotated[int, Field(ge=0, le=150)]

类型检查工具

Mypy 配置
# pyproject.toml
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
check_untyped_defs = true
disallow_untyped_decorators = true
no_implicit_optional = true
warn_redundant_casts = true
warn_unused_configs = true

# Per-module overrides
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false

[[tool.mypy.overrides]]
module = "third_party.*"
ignore_missing_imports = true
Pyright 配置
// pyrightconfig.json
{
  "include": ["src"],
  "exclude": ["**/node_modules", "**/__pycache__"],
  "typeCheckingMode": "strict",
  "pythonVersion": "3.12",
  "reportMissingImports": true,
  "reportMissingTypeStubs": false,
  "reportUnusedImport": true,
  "reportUnusedVariable": true
}
运行类型检查器
# Mypy
mypy src/ --strict
mypy src/ --ignore-missing-imports

# Pyright (faster, VS Code default)
pyright src/

# With uv
uv run mypy src/

最佳实践

1. 使用原生泛型(3.9+)
# Preferred (Python 3.9+)
items: list[str] = []
mapping: dict[str, int] = {}

# Avoid (old style)
from typing import List, Dict
items: List[str] = []  # Deprecated
2. 优先使用协议而非 ABC
# Preferred - structural typing
from typing import Protocol

class Serializable(Protocol):
    def to_json(self) -> str: ...

# Less flexible - nominal typing
from abc import ABC, abstractmethod

class SerializableABC(ABC):
    @abstractmethod
    def to_json(self) -> str: ...
3. 使用抽象集合类型
from collections.abc import Iterable, Sequence, Mapping, MutableMapping

# Prefer abstract types for function parameters
def process_items(items: Iterable[str]) -> list[str]:
    return [item.upper() for item in items]

def lookup(data: Mapping[str, int], key: str) -> int | None:
    return data.get(key)

# Works with any iterable/mapping
process_items(["a", "b"])      # list
process_items({"a", "b"})      # set
process_items(("a", "b"))      # tuple
process_items(x for x in "ab") # generator
4. 渐进式类型标注策略
# Start with public API
def public_function(data: dict[str, Any]) -> list[str]:
    return _internal_helper(data)

# Type internal helpers later
def _internal_helper(data):  # Untyped initially
    ...

# Aim for 80%+ coverage on new code
# Use # type: ignore sparingly
5. 记录复杂类型
from typing import TypeAlias

# Use type aliases for complex types
JsonPrimitive: TypeAlias = str | int | float | bool | None
JsonArray: TypeAlias = list["JsonValue"]
JsonObject: TypeAlias = dict[str, "JsonValue"]
JsonValue: TypeAlias = JsonPrimitive | JsonArray | JsonObject

def parse_json(text: str) -> JsonValue:
    """Parse JSON string into typed Python value."""
    import json
    return json.loads(text)

补充参考资料

如需了解本指南未涵盖的高级类型标注模式,请参阅:

  • 高级类型标注模式 - 泛型仓储模式、判别联合、使用 Self 的构建器模式、ParamSpec 装饰器、使用重载的条件类型、类型化装饰器工厂、包含类方法的 Protocol、类型化上下文变量、递归类型、类型化事件系统

评论

支持 Markdown