I've been using the following to "freeze" class instances in Python so that if I unwittingly define a new instance variable it brings up an error rather than just letting me do so.
class FrozenClass(object):
__isfrozen = False
def __setattr__(self, key, value):
if self.__isfrozen and key not in dir(self):
raise TypeError( "%r is a frozen class" % self )
object.__setattr__(self, key, value)
def _freeze(self):
self.__isfrozen = True
## so that if you're inheriting a frozen class you can unfreeze it
def _unfreeze(self):
self.__isfrozen = False
Which works as so:
>>> class Foo(FrozenClass):
... def __init__(self):
... self.a = 1
... self._freeze()
...
>>> myInstance = Foo()
>>> myInstance.A = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/XXX/Desktop/Git/functions/FrozenClass.py", line 6, in __setattr__
raise TypeError( "%r is a frozen class" % self )
TypeError: <__main__.Foo object at 0x10075c4e0> is a frozen class
>>>
However I've been working with a global data object which I've made static and it doesn't work. I've tried playing around with it but to no avail. Here it is as it currently stands:
## doesn't currently work. Not sure.
class FrozenStaticClass(object):
__isfrozen = False
def __setattr__(cls, key, value):
if cls.__isfrozen and key not in dir(cls):
raise TypeError( "%r is a frozen class" % cls )
object.__setattr__(cls, key, value)
@classmethod
def _freeze(cls):
cls.__isfrozen = True
@classmethod
def _unfreeze(cls):
cls.__isfrozen = False
How do I get it to freeze static classes?
Edit: @volcano suggested using slots but it doesn't seem to work for class variables.