PyCharm中Python shelve模块类型提示警告问题求助
解决Python shelve模块在PyCharm中的类型提示警告问题
问题重现
使用shelve模块操作数据时,PyCharm 2022.2.3社区版会触发类型提示警告,但代码实际运行正常:
- 直接取值调用
len()时,IDE提示:Expected type 'Sized', got 'object' insteadimport shelve s = shelve.open("testshelf.db") s["my_list"]: list = [1, 2, 3, 4] print(len(s["my_list"])) - 尝试用
Dict注解函数参数后,传入shelve实例时提示:Expected type 'dict[str, list]', got 'Shelf[object]' insteadimport shelve from typing import Dict s = shelve.open("testshelf.db") s["my_list"]: list = [1, 2, 3, 4] def foo(s_: Dict[str, list]): print(len(s_["my_list"])) foo(s)
解决方案
1. 给Shelf实例指定泛型类型注解
shelve.open()返回的是Shelf对象(继承自MutableMapping),默认值类型为object,显式指定泛型参数即可让IDE识别具体类型:
import shelve from typing import List # 明确指定Shelf的键为str,值为List[int] s: shelve.Shelf[str, List[int]] = shelve.open("testshelf.db") s["my_list"] = [1, 2, 3, 4] print(len(s["my_list"])) # 无类型提示警告
2. 对单个取值做类型断言
如果不需要全局指定Shelf的类型,可针对取出的单个值做类型断言:
import shelve from typing import List s = shelve.open("testshelf.db") s["my_list"] = [1, 2, 3, 4] # 方式1:赋值时指定类型 my_list: List[int] = s["my_list"] print(len(my_list)) # 方式2:直接在取值处做断言 print(len(s["my_list"] # type: List[int]))
3. 函数参数使用Shelf类型而非Dict
shelve实例不是标准dict,函数参数应注解为Shelf并指定泛型:
import shelve from typing import List s = shelve.open("testshelf.db") s["my_list"] = [1, 2, 3, 4] def foo(s_: shelve.Shelf[str, List[int]]): print(len(s_["my_list"])) foo(s) # 无类型提示警告
原因说明
shelve.Shelf的默认类型注解中,值的类型被设为object,IDE无法自动推断其具备Sized(支持len())等特性。通过显式指定泛型参数或类型断言,能告诉IDE具体的类型信息,从而消除警告。
内容的提问来源于stack exchange,提问作者ZombieGreedo
相关产品推荐
相关产品推荐

