What does frozen mean for dataclasses?

15,917

In Python, "frozen" means an object cannot be modified. For example, consider set and frozenset:

>>> s = set((1, 2, 3))
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> fs = frozenset((1, 2, 3))
>>> fs
frozenset({1, 2, 3})
>>> fs.add(4)
...
AttributeError: 'frozenset' object has no attribute 'add'

Likewise, creating a dataclass with frozen=True means its instances are frozen and cannot be changed.

Be aware that frozen only applies to the dataclass instance itself – a frozen dataclass can contain mutable items such as lists, and a regular dataclass can contain frozen/immutable items such as tuples.


The point of frozen objects is to avoid accidental modification, and to guarantee a consistent value.

  • The former is advantageous to avoid bugs. When an object is not intended to be modified, making it frozen reveals accidental modification via an immediate error.
  • The latter allows use as immutable object, for example the keys of a dict. A frozen dataclass is by default hashable and suitable as a dict key.
from dataclasses import dataclass

@dataclass(frozen=True)
class Frozen:
    x: int
    y: int

named_points = {Frozen(0, 0): "Origin"}

Note that hashability does not just depend on the dataclass but is recursive – a frozen dataclass containing a list is not hashable, because the list is not hashable.

Share:
15,917
Fl4ggi LP
Author by

Fl4ggi LP

Updated on June 04, 2022

Comments

  • Fl4ggi LP
    Fl4ggi LP about 2 years

    What's the difference between @dataclass(frozen=True) and @dataclass(frozen=False)? When should I use which?

    • khelwood
      khelwood over 3 years
      Do you want instances of your data class to be mutable or immutable?
    • Fl4ggi LP
      Fl4ggi LP over 3 years
      @khelwood That's the question... What's the difference between mutable and immutable instances? I know that strings and tuples are immutable. So do I have to set frozen True if I'm using using Strings or Tuples?
    • khelwood
      khelwood over 3 years
      Immutable means you can't change the attributes or characteristics of an object after it's initialised. What is immutability?
  • cikatomo
    cikatomo about 3 years
    is there a dataclass so frozen that we cannot even change the default values when instantiating?
  • MisterMiyagi
    MisterMiyagi about 3 years
    No. What would be the point? If the attributes are already fixed, they will all be the same instance - so just create that instance once and be done with it.
  • cikatomo
    cikatomo about 3 years
    Actually we can. Either by putting init=False in the decorator or by field(init=False). Together with frozen