0
votes

Is it possible to create a weakref of a pydantic model ?

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)

I get the following error : cannot create weak reference to 'JEdgeModel' object

Is there a way to achieve the same ?

1
Hi : could you explain a bit more of context ? Why do you need a weak reference here ? - jossefaz
You'd need to add the required field __weakref__ to BaseModel.__slots__ to make the class support weak references. - Dan D.
@DanD. thanks, if u answer i can mark it as a sollution - Ansh David
@jossefaz m creating PyQt app, i need to pass the ref of a model I need to update. I know I can update a copy of the model in a new window and send it back, but creating a weakref of the same saves me some hassle. I am not sure if its a good practice to solve the problem like this ! - Ansh David

1 Answers

1
votes

From 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.

So just add __weakref__ to your __slot__ in your model

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

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

wk = weakref.ref(a)