如何让类型检查工具识别Blender API StringProperty的正确类型?
解决Blender bpy.props API类型提示不被识别的问题
你可以通过区分类型检查环境和运行时环境,模拟StringProperty的调用行为来解决这个问题,同时完全保留原有语法和API功能:
import typing # 导入真实Blender API并重命名,避免命名冲突 from bpy.props import StringProperty as _RealStringProperty if typing.TYPE_CHECKING: # 类型检查阶段,定义模拟类让工具识别返回类型 class StringProperty: def __call__(self, **kwargs) -> str: # 仅用于类型提示,无需实现逻辑 ... else: # 运行阶段直接使用原生API StringProperty = _RealStringProperty # 保留原语法使用 my_hint: StringProperty(name="MyHint", default="test")
方案原理
- 类型检查工具(如mypy、pyright)会在
TYPE_CHECKING=True的环境下读取模拟类定义,调用StringProperty()会被识别为返回str类型,因此my_hint的类型会被正确推断为str。 - 运行时
TYPE_CHECKING=False,代码直接使用Blender原生的StringProperty,完全保留原有功能,不会影响程序运行。
扩展到其他属性类型
对于IntProperty、FloatProperty等其他bpy.props属性,只需复制相同模式,修改模拟类__call__的返回类型即可:
from bpy.props import IntProperty as _RealIntProperty if typing.TYPE_CHECKING: class IntProperty: def __call__(self, **kwargs) -> int: ... else: IntProperty = _RealIntProperty my_int: IntProperty(default=0)
内容的提问来源于stack exchange,提问作者Strike Digital
相关产品推荐
相关产品推荐

