Home

defaultfactory

Defaultfactory, often written as default_factory, is a programming concept describing a callable used to generate default values for missing entries in a data structure. The callable is invoked without arguments to supply a value when a requested key or field does not yet exist. This pattern helps avoid repeated checks for presence and ensures consistent, initialized defaults.

In Python, the term is most commonly encountered in two contexts. The collections.defaultdict class has an attribute

The second major use is in dataclasses, where the field function accepts a default_factory keyword argument.

Key characteristics: default_factory must be a zero-argument callable; it is invoked only when a new default

Historically, default factories in Python originated with the collections module (defaultdict) and later expanded to dataclasses

named
default_factory.
When
a
missing
key
is
accessed,
the
dictionary
calls
default_factory
to
create
a
value,
inserts
it
under
that
key,
and
returns
it.
If
default_factory
is
None,
missing
keys
raise
KeyError.
Typical
factories
include
list,
set,
and
int,
which
create
an
empty
container
or
a
zero
value.
This
provides
a
per-instance
default
value
produced
by
the
factory,
ensuring
that
each
object
gets
its
own
independent
mutable
value
(such
as
a
list).
For
example,
field(default_factory=list)
assigns
a
new
empty
list
to
the
field
for
each
instance.
is
needed.
It
is
especially
useful
for
mutable
defaults
and
for
lazy
initialization.
The
concept
also
appears
in
other
libraries
and
languages
with
analogous
features.
in
Python
3.7.
See
also
defaultdict,
dataclasses.field.