Search code examples
pythonpython-dataclasses

How to check if a dataclass is frozen?


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.


Solution

  • 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