PyObjC调用类时PyCharm报引用找不到警告,如何消除?
解决PyCharm对PyObjC引用的警告问题
问题背景
使用PyObjC开发时,代码可正常运行,但PyCharm弹出引用找不到的警告。环境配置:
- macOS Big Sur 11.7.4
- Python 3.10 解释器
- PyCharm 编辑器
- 通过
pip3 install -U pyobjc==9.0.1 pyobjc-core==9.0.1安装PyObjC
示例代码及警告:
import AppKit, Quartz location = AppKit.NSEvent.mouseLocation() # Cannot find reference 'NSEvent' in '__init__.py | __init__.py' position = (round(location.x), round(Quartz.CGDisplayPixelsHigh(0) - round(location.y)))# Cannot find reference 'CGDisplayPixelsHigh' in '__init__.py | __init__.py | imported module Quartz'
警告信息:
Cannot find reference 'NSEvent' in '__init__.py | __init__.py' Cannot find reference 'CGDisplayPixelsHigh' in '__init__.py | __init__.py | imported module Quartz
解决方法
1. 调整导入方式,直接导入具体类/函数
PyObjC的顶层模块是动态生成的,PyCharm的静态分析无法识别,改成直接导入具体成员能让IDE正确识别:
from AppKit import NSEvent from Quartz import CGDisplayPixelsHigh location = NSEvent.mouseLocation() position = (round(location.x), round(CGDisplayPixelsHigh(0) - round(location.y)))
2. 安装PyObjC类型存根
PyObjC从版本7+开始支持类型存根,安装对应版本的类型包可让PyCharm识别引用:
pip3 install -U types-pyobjc==9.0.1
安装完成后重启PyCharm即可生效。
3. 禁用特定未引用警告
如果以上方法无效,可针对单个代码行禁用警告:
import AppKit, Quartz location = AppKit.NSEvent.mouseLocation() # noinspection PyUnresolvedReferences position = (round(location.x), round(Quartz.CGDisplayPixelsHigh(0) - round(location.y)))# noinspection PyUnresolvedReferences
也可全局配置忽略指定引用:
- 打开
Preferences > Editor > Inspections > Python > Unresolved reference - 在
Ignore references列表中添加AppKit.NSEvent、Quartz.CGDisplayPixelsHigh等条目
4. 更新PyCharm到最新版本
旧版本PyCharm对动态生成模块的静态分析支持不足,更新到最新稳定版可能解决识别问题。
内容的提问来源于stack exchange,提问作者Алексндр Босов
相关产品推荐
相关产品推荐

