python-3.x 对属性使用注解会产生弱引用错误

k10s72fa  于 2023-04-08  发布在  Python
关注(0)|答案(1)|浏览(102)

我尝试一致地使用类型注解,但遇到了@property注解的问题。下面的代码在print语句处失败,并出现“cannot create weak reference to 'property' object”错误。

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注解移动到属性本身
  • 将A移动到外部文件,并使用install_import_hook导入
kiayqfof

kiayqfof1#

这是一个known and fixed bug(在typeguard中),修复程序于2023年4月2日作为4.0.0rc1的一部分发布。

相关问题