pyright-type-checker by bobmatnyc/claude-mpm-skills
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill pyright-type-checker# 全局安装
npm install -g pyright
# 按项目安装
npm install --save-dev pyright
# 验证安装
pyright --version
Pyright 为 Pylance 扩展提供支持:
# 安装 Pylance 扩展 (包含 pyright)
code --install-extension ms-python.vscode-pylance
# 社区包装器
pip install pyright
# 注意:仍然需要 Node.js 运行时环境
{
"include": [
"src"
],
"exclude": [
"**/node_modules",
"**/__pycache__",
".venv"
],
"typeCheckingMode": "basic",
"pythonVersion": "3.11",
"pythonPlatform": "Linux",
"reportMissingImports": true,
"reportMissingTypeStubs": false,
"strictListInference": true,
"strictDictionaryInference": true,
"strictSetInference": true
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
基础模式 (默认):
{
"typeCheckingMode": "basic",
"reportUnusedImport": "warning",
"reportUnusedVariable": "warning"
}
标准模式:
{
"typeCheckingMode": "standard",
"reportUnknownParameterType": "error",
"reportUnknownArgumentType": "error",
"reportUnknownVariableType": "error"
}
严格模式 (最大类型安全性):
{
"typeCheckingMode": "strict",
"reportPrivateUsage": "error",
"reportConstantRedefinition": "error",
"reportIncompatibleMethodOverride": "error",
"reportIncompatibleVariableOverride": "error",
"reportUnnecessaryIsInstance": "warning",
"reportUnnecessaryCast": "warning"
}
# pyright: strict
"""对此文件启用严格类型检查。"""
# pyright: basic
"""基础类型检查。"""
# pyright: reportGeneralTypeIssues=false
"""禁用特定诊断。"""
{
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic",
"python.analysis.diagnosticMode": "workspace",
"python.analysis.autoImportCompletions": true,
"python.analysis.inlayHints.functionReturnTypes": true,
"python.analysis.inlayHints.variableTypes": true,
"python.analysis.completeFunctionParens": true
}
{
"python.analysis.extraPaths": [
"./src",
"./lib"
],
"python.analysis.stubPath": "./typings",
"python.analysis.diagnosticSeverityOverrides": {
"reportUnusedImport": "warning",
"reportUnusedVariable": "warning",
"reportGeneralTypeIssues": "error"
}
}
from typing import Union
def process(value: Union[str, int]) -> str:
# Pyright 基于 isinstance 收窄类型
if isinstance(value, str):
return value.upper() # 此处 value 是 str
else:
return str(value) # 此处 value 是 int
# 类型守卫
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_list(items: list[object]) -> None:
if is_str_list(items):
# 此处 items 是 list[str]
print(", ".join(items))
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
class Circle:
def draw(self) -> None:
print("Drawing circle")
def render(obj: Drawable) -> None:
obj.draw()
# 适用于结构化类型
render(Circle()) # ✓ 无需显式继承
from typing import TypedDict, NotRequired
class User(TypedDict):
name: str
age: int
email: NotRequired[str] # Python 3.11+ 中可选
def create_user(data: User) -> None:
print(data["name"]) # ✓ 类型安全
# print(data["missing"]) # ✗ 错误
user: User = {
"name": "Alice",
"age": 30
} # ✓ email 是可选的
from typing import Literal
Mode = Literal["read", "write", "append"]
def open_file(mode: Mode) -> None:
...
open_file("read") # ✓
open_file("delete") # ✗ 错误
from typing import TypeVar, Generic, Sequence
T_co = TypeVar("T_co", covariant=True)
T_contra = TypeVar("T_contra", contravariant=True)
class Reader(Generic[T_co]):
def read(self) -> T_co: ...
class Writer(Generic[T_contra]):
def write(self, item: T_contra) -> None: ...
# 协变:Reader[Dog] 是 Reader[Animal] 的子类型
# 逆变:Writer[Animal] 是 Writer[Dog] 的子类型
from typing import ParamSpec, TypeVar, Callable
P = ParamSpec("P")
R = TypeVar("R")
def add_logging(f: Callable[P, R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"Calling {f.__name__}")
return f(*args, **kwargs)
return wrapper
@add_logging
def greet(name: str, age: int) -> str:
return f"Hello {name}, {age}"
# 类型安全:greet("Alice", 30)
from typing import TypeAlias
# 简单别名
UserId: TypeAlias = int
Username: TypeAlias = str
# 泛型别名
from collections.abc import Sequence
Vector: TypeAlias = Sequence[float]
# 复杂别名
JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None
name: Type Check
on: [push, pull_request]
jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install pyright
run: npm install -g pyright
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run pyright
run: pyright
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: pyright
name: pyright
entry: pyright
language: node
types: [python]
pass_filenames: false
additional_dependencies: ['pyright@1.1.350']
.PHONY: typecheck typecheck-strict
typecheck:
pyright
typecheck-strict:
pyright --level strict
typecheck-watch:
pyright --watch
typecheck-stats:
pyright --stats
{
"// mypy: disallow_untyped_defs": "reportUntypedFunctionDecorator",
"// mypy: disallow_any_generics": "reportMissingTypeArgument",
"// mypy: warn_return_any": "reportUnknownArgumentType",
"// mypy: strict_equality": "reportUnnecessaryComparison",
"// mypy: warn_unused_ignores": "reportUnnecessaryTypeIgnoreComment"
}
# mypy: ignore-errors
# ↓ pyright 等效
# pyright: reportGeneralTypeIssues=false
# type: ignore
# ↓ pyright 等效
# pyright: ignore
# type: ignore[error-code]
# ↓ pyright 等效
# pyright: ignore[reportGeneralTypeIssues]
{
"typeCheckingMode": "basic",
"include": ["src/new_module"],
"exclude": ["src/legacy"],
"reportMissingImports": true,
"reportMissingTypeStubs": false
}
# 创建性能基准
pyright --stats --createstub
# 更改后比较
pyright --stats
# 快速增量检查
pyright --watch
# 指定路径
pyright --watch src/
{
"executionEnvironments": [
{
"root": "src",
"pythonVersion": "3.11"
},
{
"root": "tests",
"pythonVersion": "3.11",
"extraPaths": ["src"]
}
]
}
from typing import Optional
def get_user(user_id: int) -> Optional[str]:
return "Alice" if user_id == 1 else None
# pyright 1.1.200 之前
user = get_user(1)
if user is not None:
print(user.upper())
# 使用 pyright 类型收窄
user = get_user(1)
if user: # 收窄为 str
print(user.upper())
from typing import Union
def process(value: Union[str, list[str]]) -> str:
if isinstance(value, list):
return ", ".join(value) # value 是 list[str]
return value # value 是 str
from typing import overload, Literal
@overload
def open_file(path: str, mode: Literal["r"]) -> str: ...
@overload
def open_file(path: str, mode: Literal["rb"]) -> bytes: ...
def open_file(path: str, mode: str) -> str | bytes:
if mode == "rb":
return b"binary data"
return "text data"
# 类型安全使用
text: str = open_file("file.txt", "r")
data: bytes = open_file("file.bin", "rb")
from typing import Never
def assert_never(value: Never) -> Never:
raise AssertionError(f"Unexpected value: {value}")
def handle_status(status: Literal["success", "error"]) -> None:
if status == "success":
print("OK")
elif status == "error":
print("Failed")
else:
assert_never(status) # 穷尽性检查
# 典型项目 (10K 行)
# mypy: ~5-10 秒
# pyright: ~1-2 秒
# 大型项目 (100K 行)
# mypy: ~60-120 秒
# pyright: ~10-20 秒
Pyright 优势:
mypy 优势:
{
"typeCheckingMode": "basic",
"reportMissingImports": true,
"reportUndefinedVariable": true
}
{
"typeCheckingMode": "standard",
"reportUnknownParameterType": "warning",
"reportUnknownArgumentType": "warning"
}
# 为第三方包生成存根
pyright --createstub package_name
# 自定义存根目录
mkdir -p typings
{
"python.analysis.inlayHints.variableTypes": true,
"python.analysis.inlayHints.functionReturnTypes": true,
"python.analysis.inlayHints.callArgumentNames": true
}
# 检查类型完整性
pyright --stats
# 输出:
# Files analyzed: 42
# Lines of code: 3,421
# Type completeness: 87.3%
# 避免宽泛的忽略
# pyright: ignore # ✗ 过于宽泛
# 优先使用特定忽略
# pyright: ignore[reportGeneralTypeIssues] # ✓ 特定
# 或修复问题
value: str = cast(str, unknown_value) # ✓ 最佳
{
"extraPaths": ["src", "lib"],
"stubPath": "typings",
"venvPath": ".",
"venv": ".venv"
}
# 为包生成存根
pyright --createstub requests
# 自定义存根位置
pyright --createstub requests --outputdir typings
{
"exclude": [
"**/node_modules",
"**/__pycache__",
".venv",
"build",
"dist"
]
}
{
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic",
"python.analysis.diagnosticMode": "workspace"
}
官方资源:
社区资源:
相关技能:mypy, FastAPI, Django, pytest 令牌计数:~3,850 令牌
每周安装
68
仓库
GitHub 星标
18
首次出现
2026年1月23日
安全审计
安装于
claude-code52
gemini-cli51
codex51
opencode50
cursor48
github-copilot48
# Global installation
npm install -g pyright
# Per-project installation
npm install --save-dev pyright
# Verify installation
pyright --version
Pyright powers Pylance extension:
# Install Pylance extension (includes pyright)
code --install-extension ms-python.vscode-pylance
# Community wrapper
pip install pyright
# Note: Still requires Node.js runtime
{
"include": [
"src"
],
"exclude": [
"**/node_modules",
"**/__pycache__",
".venv"
],
"typeCheckingMode": "basic",
"pythonVersion": "3.11",
"pythonPlatform": "Linux",
"reportMissingImports": true,
"reportMissingTypeStubs": false,
"strictListInference": true,
"strictDictionaryInference": true,
"strictSetInference": true
}
Basic Mode (Default):
{
"typeCheckingMode": "basic",
"reportUnusedImport": "warning",
"reportUnusedVariable": "warning"
}
Standard Mode :
{
"typeCheckingMode": "standard",
"reportUnknownParameterType": "error",
"reportUnknownArgumentType": "error",
"reportUnknownVariableType": "error"
}
Strict Mode (Maximum type safety):
{
"typeCheckingMode": "strict",
"reportPrivateUsage": "error",
"reportConstantRedefinition": "error",
"reportIncompatibleMethodOverride": "error",
"reportIncompatibleVariableOverride": "error",
"reportUnnecessaryIsInstance": "warning",
"reportUnnecessaryCast": "warning"
}
# pyright: strict
"""Strict type checking for this file."""
# pyright: basic
"""Basic type checking."""
# pyright: reportGeneralTypeIssues=false
"""Disable specific diagnostics."""
{
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic",
"python.analysis.diagnosticMode": "workspace",
"python.analysis.autoImportCompletions": true,
"python.analysis.inlayHints.functionReturnTypes": true,
"python.analysis.inlayHints.variableTypes": true,
"python.analysis.completeFunctionParens": true
}
{
"python.analysis.extraPaths": [
"./src",
"./lib"
],
"python.analysis.stubPath": "./typings",
"python.analysis.diagnosticSeverityOverrides": {
"reportUnusedImport": "warning",
"reportUnusedVariable": "warning",
"reportGeneralTypeIssues": "error"
}
}
from typing import Union
def process(value: Union[str, int]) -> str:
# Pyright narrows type based on isinstance
if isinstance(value, str):
return value.upper() # value is str here
else:
return str(value) # value is int here
# Type guards
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_list(items: list[object]) -> None:
if is_str_list(items):
# items is list[str] here
print(", ".join(items))
from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None: ...
class Circle:
def draw(self) -> None:
print("Drawing circle")
def render(obj: Drawable) -> None:
obj.draw()
# Works with structural typing
render(Circle()) # ✓ No explicit inheritance needed
from typing import TypedDict, NotRequired
class User(TypedDict):
name: str
age: int
email: NotRequired[str] # Optional in Python 3.11+
def create_user(data: User) -> None:
print(data["name"]) # ✓ Type-safe
# print(data["missing"]) # ✗ Error
user: User = {
"name": "Alice",
"age": 30
} # ✓ email is optional
from typing import Literal
Mode = Literal["read", "write", "append"]
def open_file(mode: Mode) -> None:
...
open_file("read") # ✓
open_file("delete") # ✗ Error
from typing import TypeVar, Generic, Sequence
T_co = TypeVar("T_co", covariant=True)
T_contra = TypeVar("T_contra", contravariant=True)
class Reader(Generic[T_co]):
def read(self) -> T_co: ...
class Writer(Generic[T_contra]):
def write(self, item: T_contra) -> None: ...
# Covariance: Reader[Dog] is subtype of Reader[Animal]
# Contravariance: Writer[Animal] is subtype of Writer[Dog]
from typing import ParamSpec, TypeVar, Callable
P = ParamSpec("P")
R = TypeVar("R")
def add_logging(f: Callable[P, R]) -> Callable[P, R]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"Calling {f.__name__}")
return f(*args, **kwargs)
return wrapper
@add_logging
def greet(name: str, age: int) -> str:
return f"Hello {name}, {age}"
# Type-safe: greet("Alice", 30)
from typing import TypeAlias
# Simple alias
UserId: TypeAlias = int
Username: TypeAlias = str
# Generic alias
from collections.abc import Sequence
Vector: TypeAlias = Sequence[float]
# Complex alias
JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None
name: Type Check
on: [push, pull_request]
jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install pyright
run: npm install -g pyright
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run pyright
run: pyright
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: pyright
name: pyright
entry: pyright
language: node
types: [python]
pass_filenames: false
additional_dependencies: ['pyright@1.1.350']
.PHONY: typecheck typecheck-strict
typecheck:
pyright
typecheck-strict:
pyright --level strict
typecheck-watch:
pyright --watch
typecheck-stats:
pyright --stats
{
"// mypy: disallow_untyped_defs": "reportUntypedFunctionDecorator",
"// mypy: disallow_any_generics": "reportMissingTypeArgument",
"// mypy: warn_return_any": "reportUnknownArgumentType",
"// mypy: strict_equality": "reportUnnecessaryComparison",
"// mypy: warn_unused_ignores": "reportUnnecessaryTypeIgnoreComment"
}
# mypy: ignore-errors
# ↓ pyright equivalent
# pyright: reportGeneralTypeIssues=false
# type: ignore
# ↓ pyright equivalent
# pyright: ignore
# type: ignore[error-code]
# ↓ pyright equivalent
# pyright: ignore[reportGeneralTypeIssues]
{
"typeCheckingMode": "basic",
"include": ["src/new_module"],
"exclude": ["src/legacy"],
"reportMissingImports": true,
"reportMissingTypeStubs": false
}
# Create performance baseline
pyright --stats --createstub
# Compare after changes
pyright --stats
# Fast incremental checking
pyright --watch
# With specific path
pyright --watch src/
{
"executionEnvironments": [
{
"root": "src",
"pythonVersion": "3.11"
},
{
"root": "tests",
"pythonVersion": "3.11",
"extraPaths": ["src"]
}
]
}
from typing import Optional
def get_user(user_id: int) -> Optional[str]:
return "Alice" if user_id == 1 else None
# Before pyright 1.1.200
user = get_user(1)
if user is not None:
print(user.upper())
# With pyright type narrowing
user = get_user(1)
if user: # Narrows to str
print(user.upper())
from typing import Union
def process(value: Union[str, list[str]]) -> str:
if isinstance(value, list):
return ", ".join(value) # value is list[str]
return value # value is str
from typing import overload, Literal
@overload
def open_file(path: str, mode: Literal["r"]) -> str: ...
@overload
def open_file(path: str, mode: Literal["rb"]) -> bytes: ...
def open_file(path: str, mode: str) -> str | bytes:
if mode == "rb":
return b"binary data"
return "text data"
# Type-safe usage
text: str = open_file("file.txt", "r")
data: bytes = open_file("file.bin", "rb")
from typing import Never
def assert_never(value: Never) -> Never:
raise AssertionError(f"Unexpected value: {value}")
def handle_status(status: Literal["success", "error"]) -> None:
if status == "success":
print("OK")
elif status == "error":
print("Failed")
else:
assert_never(status) # Exhaustiveness check
# Typical project (10K lines)
# mypy: ~5-10 seconds
# pyright: ~1-2 seconds
# Large project (100K lines)
# mypy: ~60-120 seconds
# pyright: ~10-20 seconds
Pyright Advantages :
mypy Advantages :
{
"typeCheckingMode": "basic",
"reportMissingImports": true,
"reportUndefinedVariable": true
}
{
"typeCheckingMode": "standard",
"reportUnknownParameterType": "warning",
"reportUnknownArgumentType": "warning"
}
# Generate stubs for third-party packages
pyright --createstub package_name
# Custom stubs directory
mkdir -p typings
{
"python.analysis.inlayHints.variableTypes": true,
"python.analysis.inlayHints.functionReturnTypes": true,
"python.analysis.inlayHints.callArgumentNames": true
}
# Check type completeness
pyright --stats
# Output:
# Files analyzed: 42
# Lines of code: 3,421
# Type completeness: 87.3%
# Avoid broad ignores
# pyright: ignore # ✗ Too broad
# Prefer specific ignores
# pyright: ignore[reportGeneralTypeIssues] # ✓ Specific
# Or fix the issue
value: str = cast(str, unknown_value) # ✓ Best
{
"extraPaths": ["src", "lib"],
"stubPath": "typings",
"venvPath": ".",
"venv": ".venv"
}
# Generate stubs for package
pyright --createstub requests
# Custom stub location
pyright --createstub requests --outputdir typings
{
"exclude": [
"**/node_modules",
"**/__pycache__",
".venv",
"build",
"dist"
]
}
{
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic",
"python.analysis.diagnosticMode": "workspace"
}
Official :
Community :
Related Skills : mypy, FastAPI, Django, pytest Token Count : ~3,850 tokens
Weekly Installs
68
Repository
GitHub Stars
18
First Seen
Jan 23, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code52
gemini-cli51
codex51
opencode50
cursor48
github-copilot48
FastAPI官方技能:Python Web开发最佳实践与CLI工具使用指南
1,100 周安装