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.
Having a variable in Java be
finalbasically means that once you assign to a variable, you may not reassign that variable to point to another object. It actually doesn’t mean that the object can’t be modified. For example, the following Java code works perfectly well:but the following wouldn’t even compile:
So your question is about whether
finalexists in Python. It does not.However, Python does have immutable data structures. For example, while you can mutate a
list, you can’t mutate atuple. You can mutate asetbut not afrozenset, etc.My advice would be to just not worry about enforcing non-mutation at the language level and simply concentrate on making sure that you don’t write any code which mutates these objects after they’re assigned.