在 VS Code 中配置 Pylance 识别 Image.core.* 扩展模块的自动补全与类型提示。
解读
- 现象:在 VS Code 里写
from PIL import Image后,再调用Image.core.*相关接口(如Image.core.resize、Image.core.convert等)时,Pylance 报 “Cannot find declaration” 或 “Unknown member”,没有补全,也没有类型信息。 - 根源:
Image.core是 Pillow 在运行时通过import _imaging动态加载的 C 扩展模块,源码里用from . import _imaging as core再sys.modules['PIL.Image.core'] = core做了一次“伪命名空间”注入。- Pylance 基于静态分析,只能看到 Python 文件,找不到
_imaging.cp39-win_amd64.pyd这类二进制,于是认为Image.core不存在。
- 国内面试场景:
- 大厂/外企 Python 后端、AI 平台、质检流水线都会用 Pillow 做解码/预处理,CI 静态检查必须过。
- 面试官想确认候选人是否“既懂 Pillow 源码,又能解决工程化痛点”,而不是只会
pip install。
知识点
- Pylance 类型存根(stub)加载顺序:
- 优先使用包内自带的
py.typed标记;若无,则查找site-packages/PIL-stubs或用户自定义 stub 路径。
- 优先使用包内自带的
- Pillow 的 C 扩展入口:
_imaging模块在 C 源码_imaging.c中通过PyInit__imaging导出,函数签名在 Python 层无对应.py文件。
- stub 文件语法:
- 用
...占位函数体,类型注解用Image.core.resize(__data: bytes, __size: tuple[int, int]) -> bytes: ...即可。
- 用
- VS Code 设置粒度:
- 全局
python.analysis.stubPath与用户工作区.vscode/settings.json可叠加;CI 场景下推荐把 stub 随仓库存放,保证团队一致。
- 全局
- 国内镜像加速:
- 若 Pillow 需要源码编译 stub,建议先
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pillow,再提取头文件,避免外网超时。
- 若 Pillow 需要源码编译 stub,建议先
答案
步骤 1:确认 Pillow 已安装并包含 C 扩展
python -c "from PIL import _imaging, Image; print(Image.core)"
能输 <module 'PIL._imaging'> 说明扩展正常。
步骤 2:在工作区新建存根目录
project
├─ .vscode
│ └─ settings.json
└─ stubs
└─ PIL
├─ __init__.pyi
├─ Image.pyi
└─ _imaging.pyi # 核心文件
步骤 3:撰写 _imaging.pyi(最小可用版)
# stubs/PIL/_imaging.pyi
from typing import Sequence
def resize(__data: bytes, __size: tuple[int, int], __resample: int = 1) -> bytes: ...
def convert(__data: bytes, __mode: str, __new_mode: str) -> bytes: ...
def new(__mode: str, __size: tuple[int, int]) -> bytes: ...
def open_pillow(__filename: str) -> int: ... # 示例句柄
步骤 4:在 Image.pyi 里把 core 显式导出
# stubs/PIL/Image.pyi
from . import _imaging as core
__all__ = ["core", "Image", ...]
步骤 5:告诉 Pylance 额外 stub 路径
.vscode/settings.json
{
"python.analysis.stubPath": "${workspaceFolder}/stubs",
"python.analysis.autoSearchPaths": true,
"python.analysis.useImportHeuristic": true
}
步骤 6:重启 VS Code,验证
from PIL import Image
out = Image.core.resize(b'raw', (640, 480)) # 现在能补全,类型为 bytes
步骤 7(可选):CI 自动化
把 stubs 目录加入仓库,pre-commit 里运行
python -m pyright --verifytypes PIL
保证静态检查通过。
拓展思考
- 如果 Pillow 升级,C 扩展接口变了怎么办?
- 在 CI 里加一条脚本:用
ctypes或cppyy反射_imaging.pyd的函数表,自动生成*.pyi,实现“自描述” stub,一劳永逸。
- 在 CI 里加一条脚本:用
- 动态属性注入场景:
- 某些插件在运行时给
Image.core加函数,例如pyproject.toml中的pillow-plugin。此时 stub 里可写def __getattr__(name: str) -> Any: ...,兼顾扩展性与类型安全。
- 某些插件在运行时给
- 与 numpy 桥接:
Image.core.toarray若返回numpy.ndarray,stub 里可直接标注-> ndarray[Any, dtype[uint8]],但需from numpy import ndarray, dtype, uint8,并保证团队统一 numpy 版本,避免类型冲突。
- 性能与合规:
- 国内某些涉密项目要求“零外网”,可把 stub 目录打为
wheel私源,通过devpi分发,既解决补全,也满足审计。
- 国内某些涉密项目要求“零外网”,可把 stub 目录打为