Skip to content
Advertisement

`final` keyword equivalent for variables in Python?

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.

Advertisement

Answer

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:

public final List<String> messages = new LinkedList<String>();

public void addMessage()
{
    messages.add("Hello World!");  // this mutates the messages list
}

but the following wouldn’t even compile:

public final List<String> messages = new LinkedList<String>();

public void changeMessages()
{
    messages = new ArrayList<String>();  // can't change a final variable
}

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 a tuple. You can mutate a set but not a frozenset, 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.

Advertisement