I have the following class where I have defined couple of class variables and a helper class method where I am updating the value of these class variables based on some condition.
class Foo:
_UPDATED_AT: datetime = datetime.datetime(2000, 1, 1)
STATUS: bool = False
@classmethod
def bar(cls):
# updated the class variable from here only based on some condition
if some_cond:
cls.STATUS = True
cls.UPDATED_AT = datetime.datetime.now()
return cls.STATUS
I want to 1) prevent these class variables from being updated(i.e. being set) directly outside of the class, 2) but to be able to update the classvar from the class method, so semantically something behaving like a private class variable in C++.
I was able to achieve the first of the two requirements by using the a metaclass which basically blocks the attributing setting
class MyMeta(type):
def __setattr__(cls, key, value):
raise AttributeError(f"Can't set {cls}.{key}")
However as expected this also prevents updates from happening within the class. I am not sure if this is possible to achieve with pure python but basically I guess somehow I need to detect if the update is happening from inside or outside of the class.
Any pointers if I can achieve this ?