Advantages of Default Factory in Dataclasses

Paul Bryan pbryan at anode.ca
Tue Nov 16 10:17:26 EST 2021


On Tue, 2021-11-16 at 17:04 +0400, Abdur-Rahmaan Janhangeer wrote:

> A simple question: why do we need field(default_factory ) in
> dataclasses?

To initialize a default value when a new instance of the dataclass is
created. For example, if you want a field to default to a dict. A new
dict is created for each instance of the dataclass created.

> Why not make that field as an attribute return a function?

I do not understand the question.

> Useful implementation examples / use cases appreciated.

Any case where a you want a dataclass field to default to a mutable
value. Examples: dicts, lists, other dataclasses.

Paul



More information about the Python-list mailing list