
pycharm在处理继承自`functools.cached_property`的自定义装饰器时,其类型检查器可能无法正确推断类型,导致类型错误被忽略,而`mypy`则能正确识别。本文将探讨pycharm此行为的原因,并提供一种通过重命名自定义装饰器类来“欺骗”pycharm类型检查器的临时解决方案,以确保类型安全。
在Python开发中,描述符(descriptor)是一种强大的机制,允许我们自定义属性的访问行为。functools.cached_property就是一个常见的描述符,它将一个方法转换为一个只计算一次的属性。然而,当开发者尝试创建自定义的、继承自cached_property的描述符时,可能会遇到PyCharm类型检查器行为异常的问题。
考虑以下代码示例,我们定义了一个名为result_property的自定义描述符,它继承自cached_property,并尝试在PyCharm中进行类型检查:
from functools import cached_property
from collections.abc import Callable
from typing import TypeVar, Generic, Any, overload, Union
T = TypeVar("T")
class result_property(cached_property, Generic[T]):
    def __init__(self, func: Callable[[Any], T]) -> None:
        super().__init__(func)
    def __set_name__(self, owner: type[Any], name: str) -> None:
        super().__set_name__(owner, name)
    @overload
    def __get__(self, instance: None, owner: Union[type[Any], None] = None) -> 'result_property[T]': ...
    @overload
    def __get__(self, instance: object, owner: Union[type[Any], None] = None) -> T: ...
    def __get__(self, instance, owner=None):
        return super().__get__(instance, owner)
def func_str(s: str) -> None:
    print(s)
class Foo:
    @result_property
    def prop_int(self) -> int:
        return 1
foo = Foo()
func_str(foo.prop_int) # 期望此处出现类型错误在这段代码中,foo.prop_int被定义为返回int类型。当将其作为参数传递给期望str类型的func_str函数时,理论上应该引发类型错误。mypy(一个流行的Python静态类型检查器)能够正确识别这个错误:
tmp.py:38: error: Argument 1 to "func_str" has incompatible type "int"; expected "str" [arg-type] Found 1 error in 1 file (checked 1 source file)
然而,PyCharm 2023.2.3(社区版)的类型检查器却报告此代码是正确的,未能识别出潜在的类型不匹配问题。这表明PyCharm在处理这种自定义描述符时,其类型推断机制可能存在局限性。
根据观察,PyCharm的静态类型检查器似乎对某些内置或常用名称(如cached_property)采用了硬编码的逻辑,而非完全依赖于通用的类型推断系统来解析装饰器或描述符的复杂类型行为。这意味着,它可能不是通过分析result_property的继承链和__get__方法的重载签名来推断类型,而是简单地查找特定的名称。
为了验证这一点,我们可以尝试一个简化的、甚至有些“虚假”的cached_property实现。如果PyCharm仅仅是根据名称进行判断,那么即使是一个不完整的实现,只要名称匹配,也可能触发其预期的类型检查行为:
def cached_property(func): # 注意:这里不是functools.cached_property
    def foo(self):
        pass # 这是一个不完整的实现,但名称是'cached_property'
    return foo
def func_str(s: str) -> None:
    print(s)
class Foo:
    @cached_property
    def prop_int(self) -> int:
        return 1
foo = Foo()
func_str(foo.prop_int) # 此时PyCharm会报告:Expected type 'str', got 'int' instead令人惊讶的是,即使是这样一个简化的、不完全符合cached_property行为的函数,只要其名称为cached_property,PyCharm就会正确地报告类型错误。这强烈支持了PyCharm的类型检查器在处理cached_property时,其逻辑是基于硬编码的名称而非严格的类型推断。
既然PyCharm的类型检查器似乎对cached_property这个名称有特殊的处理逻辑,那么一个直接的解决方案就是将我们自定义的描述符类也命名为cached_property。这样,PyCharm就会应用其预设的类型检查规则,从而正确地识别类型错误。
以下是修改后的代码示例:
import functools
from collections.abc import Callable
from typing import TypeVar, Generic, Any, overload, Union
T = TypeVar("T")
# 将自定义描述符的类名改为 cached_property
class cached_property(functools.cached_property, Generic[T]):
    def __init__(self, func: Callable[[Any], T]) -> None:
        super().__init__(func)
    def __set_name__(self, owner: type[Any], name: str) -> None:
        super().__set_name__(owner, name)
    @overload
    def __get__(self, instance: None, owner: Union[type[Any], None] = None) -> 'cached_property[T]': ...
    @overload
    def __get__(self, instance: object, owner: Union[type[Any], None] = None) -> T: ...
    def __get__(self, instance, owner=None):
        return super().__get__(instance, owner)
def func_str(s: str) -> None:
    print(s)
class Foo:
    @cached_property # 使用重命名后的装饰器
    def prop_int(self) -> int:
        return 1
foo = Foo()
func_str(foo.prop_int) # 此时PyCharm会报告:Expected type 'str', got 'int' instead通过将result_property类重命名为cached_property,PyCharm现在能够正确地识别出foo.prop_int的实际类型是int,并在将其传递给期望str类型的func_str时报告类型错误。
总而言之,当PyCharm在处理继承自functools.cached_property的自定义描述符时出现类型检查不准确的情况,一个有效的临时解决方案是将其类名更改为cached_property,以利用PyCharm内部对该名称的特殊处理逻辑。
以上就是PyCharm中自定义装饰器属性的类型检查问题及解决方案的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号