Search code examples
pythonpython-dataclassespython-attrs

Different objects for the same class initiated with same value while working with attrs module


I'm trying to create Model class with attrs module. I'm generating iid value with bson ObjectId which returns a unique value with every call. And generating timestamp value with time module.

While I was creating two objects with the User class, I'm seeing that both objects have same value. But they are initialized separately.

The sample code is here:

from bson import ObjectId
from attrs import asdict, define, field, validators
import time


@define
class CollectionModel:
    """ Base Class For All Collection Schema"""
    iid : str =  str(ObjectId())
    timestamp : float = time.time()

    def get_dict(self):
        return asdict(self)

@define
class User(CollectionModel):
    username : str = field(factory = str, validator=validators.instance_of(str)) 
    userType : str = field(factory = str, validator=validators.instance_of(str)) 
    password : str = field(factory = str, validator=validators.instance_of(str))


user_object1 = User()
user_object2 = User()

print(user_object1)
print(user_object2)

The output:

User(iid='620bf6910e5fa38f757e35ec', timestamp=1644951185.428748, username='', userType='', password='')
User(iid='620bf6910e5fa38f757e35ec', timestamp=1644951185.428748, username='', userType='', password='')

Here, iid and timestamp is same for both user_object1 and user_object2. But expected different. Although the objects are created separately why the values are same?


Solution

  • Your default iid is constant because you didn't wrap str(ObjectId()) into an attrs.Factory. It's created once when the class is defined & used in all instances. Same with timestamp.