Search code examples
pythonpython-dataclasses

Is it possible to freeze a dataclass object in __post_init__() or later?


I'm wondering whether it's possible to "freeze" a dataclass object in post_init() or even after an object was defined.

So instead of:

@dataclass(frozen=True)
class ClassName:
    var1: type = value

Having something like:

@dataclass
class ClassName:
     var1: type = None
def __post_init__(self):
     self.var1 = value
     FREEZE()

Or even sth like:

a = ClassName()
FREEZE(a)

Possible or not and why?


Solution

  • No, it isn't. But "frozen" can be subverted trivially, just use:

    @dataclass(frozen=True)
    class ClassName:
         var1: type = value
    def __post_init__(self):
        object.__setattr__(self, 'var1', value)