Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unmutable field on python's dataclass

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_

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading