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

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.

Leave a Comment