In Python, the convention should use the _ prefix for attribute names, which means protected and the __ prefix for private . This language is not respected by the language; programmers are expected to not write code based on non-public data.
If you really want to ensure immutability, you can use the metaclass [ docs ] (class of the class). Just change __setattr__ and __delattr__ to raise exceptions when someone tries to change it, and make it tuple (immutable list) [ docs ] .
class FooMeta(type): """A type whose .thingies attribute can't be modified.""" def __setattr__(cls, name, value): if name == "thingies": raise AttributeError("Cannot modify .thingies") else: return type.__setattr__(cls, name, value) def __delattr__(cls, name): if name == "thingies": raise AttributeError("Cannot delete .thingies") else: return type.__delattr__(cls, name) thing1, thing2, thing3 = range(3) class Foo(object): __metaclass__ = FooMeta thingies = (thing1, thing2, thing3) other = [1, 2, 3]
Examples
print Foo.thingies
Foo.other = Foo.other + [4] # no exception print Foo.other # prints "[1, 2, 3, 4]"
It would still be technically possible to change them by going through the inner class of .__dict__ class attributes, but this should be enough to hold most users, it is very difficult to completely protect Python objects.
Jeremy banks
source share