I couldn't find documentation on an equivalent of Java's final
in Python, is there such a thing?
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.
you can simulate something like that through the descriptor protocol, since it allows to define reading and setting a variable the way you wish.
http://code.activestate.com/recipes/576527/ defines a freeze function, although it doesn't work perfectly.
I would consider just leaving it mutable though.
Python indeed does not have a final type, it does have immutable types such as tuples but that is something else.
Some of the other Answers here make classes full of pseudo final variables and I prefer my class to only have a few Final types, so I suggest using an descriptor to create the final type:
If you use this class like so:
Then you will not be able to set that variable in any instance of that class. Unfortunately as with the WriteOnceReadWhenever answer you can still set the class variable.
There is no ``final'' equivalent in Python.
But, to create read-only fields of class instances, you can use the property function.
Edit: perhaps you want something like this:
Having a variable in Java be
final
basically 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
final
exists 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 aset
but 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.
Although this is an old question, I figured I would add yet another potential option: You can also use
assert
to verify a variable is set to what you originally intended it to be set to – a double checking if you will. Although this is not the same asfinal
in Java, it can be used to create a similar effect:As seen above, if
PI
were for some reason not set to3.14
, anAssertionError
would be thrown, so atry/except
block would probably be a wise addition. Regardless, it may come in handy depending on your situation.