为 pydantic 模型创建一个 weakref

creating a weakref to pydantic model

是否可以创建 pydantic 模型的弱引用?

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

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

来自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)