You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@property注解添加类型标注时出现weak reference错误的原因及解决

问题:@typechecked与@property结合时触发"cannot create weak reference to 'property' object"错误

问题复现

执行以下代码时,调用print(a.p)会抛出类型错误:

from typeguard import typechecked

@typechecked
class A:
    def __init__(self):
        self._p = 1

    @property
    def p(self) -> int:
        return self._p

a = A()
print(a.p)

错误信息:

Exception has occurred: TypeError
cannot create weak reference to 'property' object
  File "C:\Code\ExploreSims\scratch.py", line 9, in p
    def p(self) -> int:
  File "C:\Code\ExploreSims\scratch.py", line 13, in <module>
    print(a.p)
          ^^^
TypeError: cannot create weak reference to 'property' object

移除类型注解、将@typechecked移至@property本身,或是通过install_import_hook导入类,都会触发相同错误。

原因分析

typeguard的@typechecked装饰器在装饰类时,会遍历并处理类的所有成员,包括property对象。其内部实现中会尝试为这些成员创建弱引用,但Python原生的property类型不支持弱引用操作,因此直接触发TypeError。即使将装饰器直接应用在@property上,依然会因对property对象执行弱引用逻辑而报错。

解决方法

1. 仅装饰需要类型检查的方法

避免用@typechecked装饰整个类,只将其应用在需要类型校验的方法(如__init__)上:

from typeguard import typechecked

class A:
    @typechecked
    def __init__(self):
        self._p = 1

    @property
    def p(self) -> int:
        return self._p

a = A()
print(a.p)

2. 通过skip参数跳过property成员

在类装饰器中指定skip参数,排除不需要类型检查的property:

from typeguard import typechecked

@typechecked(skip=['p'])
class A:
    def __init__(self):
        self._p = 1

    @property
    def p(self) -> int:
        return self._p

a = A()
print(a.p)

3. 升级typeguard到最新版本

部分旧版本的typeguard存在该兼容性问题,升级到最新稳定版(如>=2.13.3)后,该问题已被修复,可直接使用原代码结构。

4. 手动在getter中做类型校验

如果不想依赖装饰器自动校验,可手动通过类型断言确保返回值类型:

from typing import cast

class A:
    def __init__(self):
        self._p = 1

    @property
    def p(self) -> int:
        return cast(int, self._p)

a = A()
print(a.p)

内容的提问来源于stack exchange,提问作者Oblomov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 06:37:52