Advantages of Default Factory in Dataclasses

dn PythonList at DancesWithMice.info
Tue Nov 16 14:49:34 EST 2021


On 17/11/2021 02.04, Abdur-Rahmaan Janhangeer wrote:
> A simple question: why do we need field(default_factory ) in dataclasses?
> 
> Why not make that field as an attribute return a function?
> 
> Useful implementation examples / use cases appreciated.


It's an interesting question: We could define a list (or whatever)
within __post_init__()!

Greater minds than mine may care to comment on the theory that something
defined as a dataclasses.field will be allocated as part of the class
constructor, ie lower-cost. Whereas, something defined post-init will
require extra process-time and storage-allocation. (?)

Doesn't it already return a (evaluated) function? Remember: one is not
limited to Python built-in or PSL types. Thus:

def countdown():
    return [ 10, 9, 8, 7, ..., "blast-off" ]

...
    launch_commentary:list = field( default_factory=countdown )


The use of default-values for mutables is something of a Python
'gotcha'. My use-case is that some wise-soul's decision to do things
this way prevents me from falling into that debugging "slough of despond".
(does such qualify as a "use case"?)
-- 
Regards,
=dn


More information about the Python-list mailing list