Search code examples
pythonpython-dataclasses

can you make a regular python class frozen?


It's useful to be able to create frozen dataclasses. I'm wondering if there is a way to do something similar for regular python classes (ones with an __init__ function with complex logic possibly). It would be good to prevent modification after construction in some kind of elegant way, like frozen dataclasses.


Solution

  • yes.

    All attribute access in Python is highly customizable, and this is just a feature dataclasses make use of.

    The easiest way to control attribute setting is to create a custom __setattr__ method in your class - if you want to be able to create attributes during __init__ one of the ways is to have an specific parameter to control whether each instance is frozen already, and freeze it at the end of __init__:

    class MyFrozen:
       _frozen = False
       def __init__(self, ...):
           ...
           self._frozen = True
    
       def __setattr__(self, attr, value):
           if getattr(self, "_frozen", None):
                raise AttributeError("Trying to set attribute on a frozen instance")
           return super().__setattr__(attr, value)