Python 3.9+无需typing模块声明符合PyLint规则的可调用类变量
解决PyLint提示"not-callable"的类型注解方案(无需导入types模块)
你遇到的问题是因为PyLint无法推断初始赋值为None的on_show后续会被赋值为可调用对象,因此报错E1102。以下是几种无需导入types模块的解决方案,符合Python 3.9+的原生类型支持和PyLint规则:
方案1:使用typing.Callable联合类型注解
通过typing模块的Callable明确标注类型,搭配None组成联合类型(Python 3.10+支持|语法,3.9版本用Optional兼容):
from typing import Callable, Optional def my_show(text1: str, text2: str): print('my_show', text1, text2) class ClassA: def __init__(self): # Python 3.10+ 简洁写法 self.on_show: Callable[[str, str], None] | None = None # Python 3.9 兼容写法 # self.on_show: Optional[Callable[[str, str], None]] = None def show(self, text1: str, text2: str): print('show', text1, text2) if self.on_show: self.on_show(text1, text2)
方案2:使用collections.abc.Callable(Python 3.9+原生支持)
Python 3.9+将Callable纳入了标准库的collections.abc模块,无需依赖typing也能实现类型标注:
from collections.abc import Callable def my_show(text1: str, text2: str): print('my_show', text1, text2) class ClassA: def __init__(self): self.on_show: Callable[[str, str], None] | None = None def show(self, text1: str, text2: str): print('show', text1, text2) if self.on_show: self.on_show(text1, text2)
方案3:无导入依赖的字符串形式注解
借助Python 3.7+的延迟求值注解特性,添加from __future__ import annotations后,可直接用字符串描述类型,无需导入任何模块:
from __future__ import annotations def my_show(text1: str, text2: str): print('my_show', text1, text2) class ClassA: def __init__(self): self.on_show: "Callable[[str, str], None] | None" = None def show(self, text1: str, text2: str): print('show', text1, text2) if self.on_show: self.on_show(text1, text2)
方案4:类级别声明类型注解
在类的顶层直接声明成员变量类型,初始化时仅赋值None,代码结构更清晰:
from typing import Callable def my_show(text1: str, text2: str): print('my_show', text1, text2) class ClassA: on_show: Callable[[str, str], None] | None def __init__(self): self.on_show = None def show(self, text1: str, text2: str): print('show', text1, text2) if self.on_show: self.on_show(text1, text2)
内容的提问来源于stack exchange,提问作者VladVons
相关产品推荐
相关产品推荐

