I have this dataclass:
@dataclass
class Couso:
nome: str
date: str = field(default=datetime.now(), init = False)
id_: str = field(default=key())
Being key() a simple function that returns a str on len 32.
And when i create multiple classes of it (without specifing the id_ obviously) they all share the same id_
But why does it work this way? I cant understand.
Also, would this happen again with the attribute date?
>Solution :
key is called before field is called to create the field, so that every instance will have the same default id_ attribute. It’s the same as if you had written
x = key()
@dataclass
class Couso:
...
id_ : str = field(default=x)
If you want to call key each time you create a new instance, use default_factory instead.
id_: str = field(default_factory=key) # key is not called; it's passed as an object.
The same goes for datetime.now:
date: str = field(default_factory=datetime.now, init = False)