python-typing-ops by 0xdarkmatter/claude-mods
npx skills add https://github.com/0xdarkmatter/claude-mods --skill python-typing-ops用于安全、文档化的 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
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]
# 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
Modern type hints for safe, documented Python code.
# 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
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]
# 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
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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
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:
...
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)
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"{}"))
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))
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"
| 类型 | 使用场景 |
|---|---|
| `X | None` |
list[T] | 同质列表 |
dict[K, V] | 字典 |
Callable[[Args], Ret] | 函数类型 |
TypeVar("T") | 泛型参数 |
Protocol | 结构类型 |
TypedDict | 固定键的字典 |
Literal["a", "b"] | 仅限特定值 |
Final | 不可重新赋值 |
# mypy
mypy src/ --strict
# pyright
pyright src/
# In pyproject.toml
[tool.mypy]
strict = true
python_version = "3.11"
./references/generics-advanced.md - TypeVar、ParamSpec、TypeVarTuple./references/protocols-patterns.md - 结构类型、运行时协议./references/type-narrowing.md - 守卫、isinstance、assert./references/mypy-config.md - mypy/pyright 配置./references/runtime-validation.md - Pydantic v2、typeguard、beartype./references/overloads.md - @overload 装饰器模式./scripts/check-types.sh - 使用常用选项运行类型检查器./assets/pyproject-typing.toml - 推荐的 mypy/pyright 配置这是一个基础技能,没有先决条件。
相关技能:
python-pytest-ops - 类型安全的夹具和模拟基于此技能构建:
python-async-ops - 异步类型注解python-fastapi-ops - Pydantic 模型和验证python-database-ops - SQLAlchemy 类型注解每周安装数
2
代码仓库
GitHub 星标数
8
首次出现
今天
安全审计
安装于
amp2
cline2
openclaw2
opencode2
cursor2
kimi-cli2
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
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:
...
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)
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"{}"))
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))
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"
| Type | Use Case |
|---|---|
| `X | None` |
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 |
# mypy
mypy src/ --strict
# pyright
pyright src/
# In pyproject.toml
[tool.mypy]
strict = true
python_version = "3.11"
./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/check-types.sh - Run type checkers with common options./assets/pyproject-typing.toml - Recommended mypy/pyright configThis is a foundation skill with no prerequisites.
Related Skills:
python-pytest-ops - Type-safe fixtures and mockingBuild on this skill:
python-async-ops - Async type annotationspython-fastapi-ops - Pydantic models and validationpython-database-ops - SQLAlchemy type annotationsWeekly Installs
2
Repository
GitHub Stars
8
First Seen
Today
Security Audits
Installed on
amp2
cline2
openclaw2
opencode2
cursor2
kimi-cli2
AI新闻播客制作技能:实时新闻转对话式播客脚本与音频生成
1,200 周安装