Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 521
Allen Wang Avatar asked Jul 03 '26 09:07

Allen Wang


1 Answers

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) 
like image 110
jsbueno Avatar answered Jul 06 '26 00:07

jsbueno