Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

Bson ObjectId generating same value in python dataclass objects

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?

question from:https://stackoverflow.com/questions/65864992/bson-objectid-generating-same-value-in-python-dataclass-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...