创建从weakref到pydantic的模型

2024-09-30 19:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

有可能创建一个pydantic模型的weakref吗

from pydantic import BaseModel
from uuid import UUID

class JEdgeModel(BaseModel):
    uid: UUID
    startSocket: UUID
    destnSocket: UUID

a = JEdgeModel(uid='abd6fc3f882544f5b75661c92fccbd0d', startSocket='abd6fc3f882544f5b75661c92fccbd0d', destnSocket='abd6fc3f882544f5b75661c92fccbd0d')

wk = weakref.ref(a)

我得到以下错误: cannot create weak reference to 'JEdgeModel' object

有没有办法达到同样的效果


Tags: from模型importuiduuidclassbasemodelpydantic
1条回答
网友
1楼 · 发布于 2024-09-30 19:20:39

documentation

Without a weakref variable for each instance, classes defining slots do not support weak references to its instances. If weak reference support is needed, then add 'weakref' to the sequence of strings in the slots declaration.

因此,只需将__weakref__添加到模型中的__slot__

class JEdgeModel(BaseModel):
    __slots__ = ['__weakref__']
    uid: UUID
    startSocket: UUID
    destnSocket: UUID

a = JEdgeModel(
    uid='abd6fc3f882544f5b75661c92fccbd0d',
    startSocket='abd6fc3f882544f5b75661c92fccbd0d',
    destnSocket='abd6fc3f882544f5b75661c92fccbd0d',
)

wk = weakref.ref(a)

相关问题 更多 >