4

Is there a way to check if a Python dataclass has been set to frozen? If not, would it be valuable to have a method like is_frozen in the dataclasses module to perform this check?

e.g.

from dataclasses import dataclass, is_frozen

@dataclass(frozen=True)
class Person:
    name: str
    age: int

person = Person('Alice', 25)
if not is_frozen(person):
    person.name = 'Bob'

One way to check if a dataclass has been set to frozen is to try to modify one of its attributes and catch the FrozenInstanceError exception that will be raised if it's frozen.

e.g.

from dataclasses import FrozenInstanceError
is_frozen = False
try:
    person.name = 'check_if_frozen'
except FrozenInstanceError:
    is_frozen = True

However, if the dataclass is not frozen, the attribute will be modified, which may be unwanted just for the sake of performing the check.

schliwiju
  • 43
  • 6

1 Answers1

4

Yes looks like you can retrieve parameters' information from __dataclass_params__.

It returns an instance of _DataclassParams type which is nothing but an object for holding the values of init, repr, eq, order, unsafe_hash, frozen attributes:

from dataclasses import dataclass


@dataclass(frozen=True)
class Person:
    name: str
    age: int


print(Person.__dataclass_params__)
print(Person.__dataclass_params__.frozen)

output:

_DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)
True
S.B
  • 13,077
  • 10
  • 22
  • 49
  • 1
    Thanks, it seems that this should be mentioned somewhere in the documentation. – schliwiju Apr 07 '23 at 12:27
  • 3
    I don't know why this is a dunder attribute, but if it's not documented, it's because it's not intended for public use. (The next version of Python could rename the attribute without warning, for example.) – chepner Apr 07 '23 at 12:33