views:

1015

answers:

7

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.

+2  A: 

Python has no equivalent of "final". It doesn't have "public" and "protected" either, except by naming convention. It's not that "bondage and discipline".

RichieHindle
+6  A: 

There is no such thing. In general, the Python attitude is "if you don't want this modified, just don't modify it". Clients of an API are unlikely to just poke around your undocumented internals anyway.

You could, I suppose, work around this by using tuples or namedtuples for the relevant bits of your model, which are inherently immutable. That still doesn't help with any part of your model that has to be mutable of course.

Sii
Many other classes are immutable, too: strings, ints, longs, floats.
S.Lott
+2  A: 

http://code.activestate.com/recipes/576527/ defines a freeze function, although it doesn't work perfectly.

I would consider just leaving it mutable though.

cobbal
+10  A: 

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:

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

        self.__dict__[attr] = value
Stephan202
Interesting idea
jcoon
+15  A: 

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.

Eli Courtwright
+3  A: 

An assign-once variable is a design issue. You design your application in a way that the variable is set once and once only.

However, if you want run-time checking of your design, you can do it with a wrapper around the object.

class OnePingOnlyPleaseVassily( object ):
    def __init__( self ):
        self.value= None
    def set( self, value ):
        if self.value is not None:
            raise Exception( "Already set.")
        self.value= value

someStateMemo= OnePingOnlyPleaseVassily()
someStateMemo.set( aValue ) # works
someStateMemo.set( aValue ) # fails

That's clunky, but it will detect design problems at run time.

S.Lott
+1  A: 

you can simulate something like that through the descriptor protocol, since it allows to define reading and setting a variable the way you wish.

class Foo(object):

  @property
  def myvar(self):
     # return value here

  @myvar.setter
  def myvar(self, newvalue):
     # do nothing if some condition is met

a = Foo()
print a.myvar
a.myvar = 5 # does nothing if you don't want to
UncleZeiv