Search code examples
pythonattributesimmutability

In Python, how can I make unassignable attributes (like ones marked with `final` in Java)?


Is there anything in Python that works like the final keyword in Java - i.e., to disallow assigning to a specific attribute of the instances of a class, after those instances have been created? I couldn't find anything like this in the documentation.

I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.


Solution

  • There is no final equivalent in Python. To create read-only fields of class instances, you can use the property function, or you could do something like this:

    class WriteOnceReadWhenever:
        def __setattr__(self, attr, value):
            if hasattr(self, attr):
                raise Exception("Attempting to alter read-only value")
        
            self.__dict__[attr] = value
    

    Also note that while there's @typing.final as of Python 3.8 (as Cerno mentions), that will not actually make values final at runtime.