在 VS Code 中配置 Pylance 识别 Image.core.* 扩展模块的自动补全与类型提示。

解读

  1. 现象:在 VS Code 里写 from PIL import Image 后,再调用 Image.core.* 相关接口(如 Image.core.resize、Image.core.convert 等)时,Pylance 报 “Cannot find declaration” 或 “Unknown member”,没有补全,也没有类型信息。
  2. 根源:
    • 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 不存在。
  3. 国内面试场景:
    • 大厂/外企 Python 后端、AI 平台、质检流水线都会用 Pillow 做解码/预处理,CI 静态检查必须过。
    • 面试官想确认候选人是否“既懂 Pillow 源码,又能解决工程化痛点”,而不是只会 pip install。

知识点

  1. Pylance 类型存根(stub)加载顺序:
    • 优先使用包内自带的 py.typed 标记;若无,则查找 site-packages/PIL-stubs 或用户自定义 stub 路径。
  2. Pillow 的 C 扩展入口:
    • _imaging 模块在 C 源码 _imaging.c 中通过 PyInit__imaging 导出,函数签名在 Python 层无对应 .py 文件。
  3. stub 文件语法:
    • 用 ... 占位函数体,类型注解用 Image.core.resize(__data: bytes, __size: tuple[int, int]) -> bytes: ... 即可。
  4. VS Code 设置粒度:
    • 全局 python.analysis.stubPath 与用户工作区 .vscode/settings.json 可叠加;CI 场景下推荐把 stub 随仓库存放,保证团队一致。
  5. 国内镜像加速:
    • 若 Pillow 需要源码编译 stub,建议先 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pillow,再提取头文件,避免外网超时。

答案

步骤 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

保证静态检查通过。

拓展思考

  1. 如果 Pillow 升级,C 扩展接口变了怎么办?
    • 在 CI 里加一条脚本:用 ctypes 或 cppyy 反射 _imaging.pyd 的函数表,自动生成 *.pyi,实现“自描述” stub,一劳永逸。
  2. 动态属性注入场景:
    • 某些插件在运行时给 Image.core 加函数,例如 pyproject.toml 中的 pillow-plugin。此时 stub 里可写 def __getattr__(name: str) -> Any: ...,兼顾扩展性与类型安全。
  3. 与 numpy 桥接:
    • Image.core.toarray 若返回 numpy.ndarray,stub 里可直接标注 -> ndarray[Any, dtype[uint8]],但需 from numpy import ndarray, dtype, uint8,并保证团队统一 numpy 版本,避免类型冲突。
  4. 性能与合规:
    • 国内某些涉密项目要求“零外网”,可把 stub 目录打为 wheel 私源,通过 devpi 分发,既解决补全,也满足审计。