5

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?

  • 2
    You might just want to do what's done in [this answer](https://stackoverflow.com/a/54119384/10863327). Also you could make `var1` a `property` instead of a field. – Kyle Parsons Aug 04 '21 at 17:36
  • 1
    At this time, setting `frozen=True` modifies how the `class` statement ultimately executed with `exec` is defined; it's not simply an attribute of the class. What's your reason for wanting to delay immutability? – chepner Aug 04 '21 at 17:37
  • 1
    What would be the point of this? What are you actually trying to accomplish? – juanpa.arrivillaga Aug 04 '21 at 17:38
  • Currently the variables are treated as properties and it works, however this way of assignment might not be straightforward for the user after release. – conscious_process Aug 05 '21 at 07:46
  • 2
    So if immutability could be delayed, the variables could be assigned in a clearer fashion. – conscious_process Aug 05 '21 at 07:48

1 Answers1

4

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)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172