如何为函数属性添加类型注解?PEP232与PEP484结合方法咨询
给函数属性添加类型注解的方法
针对你提到的场景,有几种方式可以在函数内部使用foo.cache前为其添加类型注解,让类型检查器(如mypy)正确识别:
方法1:使用Protocol协议(Python 3.8+)
通过定义包含cache属性的协议,让函数对象符合该协议,帮助类型检查器识别foo.cache的类型:
from typing import Protocol, Dict class HasCache(Protocol): cache: Dict[str, str] def foo(s: str) -> None: # 断言foo符合HasCache协议,明确属性类型 assert isinstance(foo, HasCache) try: print(foo.cache[s]) except Exception: print('NEW') foo.cache[s] = 'CACHE' + s foo.cache = {}
方法2:显式标注函数对象的类型
直接在函数内部标注foo的类型,明确其包含cache属性:
from typing import Callable, Dict # 定义带有cache属性的函数类型 class FooFuncWithCache(Callable[[str], None]): cache: Dict[str, str] def foo(s: str) -> None: # 标注当前函数对象的类型 foo: FooFuncWithCache try: print(foo.cache[s]) except Exception: print('NEW') foo.cache[s] = 'CACHE' + s foo.cache = {}
方法3:使用类型断言(cast)
在使用foo.cache时,用cast显式指定其类型:
from typing import cast, Dict def foo(s: str) -> None: cache = cast(Dict[str, str], foo.cache) try: print(cache[s]) except Exception: print('NEW') cache[s] = 'CACHE' + s foo.cache = {}
方法4:外部直接标注属性类型(简单直接)
如果不需要在函数内部提前标注,也可以直接在外部赋值时给foo.cache加上类型注解,部分类型检查器也能识别内部的属性类型:
from typing import Dict def foo(s: str) -> None: try: print(foo.cache[s]) except Exception: print('NEW') foo.cache[s] = 'CACHE' + s foo.cache: Dict[str, str] = {}
内容的提问来源于stack exchange,提问作者MSalters
相关产品推荐
相关产品推荐

