I am trying to generate an ObjectId that is unique for objects I make from a dataclass. Hovewer for every object I make from my class, it generates the same Id.
from dataclasses import dataclass
from bson import ObjectId
@dataclass
class B:
id: ObjectId=ObjectId()
b =B()
b.id
>>ObjectId('600c9d09c889e41a182988b0')
c =B()
c.id
>>ObjectId('600c9d09c889e41a182988b0')
I do not understand this behaviour, is it due to the dataclass keeping the same default objectId reference everytime it inits the class?
Do you have a workaround?
Since the above dataclass would be initiated as:
class B:
def __init__(self, x: ObjectId = ObjectId()):
self.id=x
The default value for the class would always be the static ObjectId
generated when the class is loaded.
In the end, I suppose dynamic values should not be passed as init params.
The correct way would be to use __post_init__
:
from dataclasses import field
@dataclass
class B:
id: ObjectId = field(init=False)
def __post_init__(self):
self.id = ObjectId()
b =B()
b.id
>>ObjectId('60104262ee527a385cb44a11')
c =B()
c.id
>>ObjectId('6010426bee527a385cb44a12')