Search code examples
pythonpropertiesinstancesetterinstance-variables

Constant instance variables?


I use @property to ensure that changes to an objects instance variables are wrapped by methods where I need to.

What about when an instance has an variable that logically should not be changed? Eg, if I'm making a class for a Process, each Process instance should have a PID attribute that will frequently be accessed but should not be changed.

What's the most Pythonic way to handle someone attempting to modify that instance variable?

  • Simply trust the user not to try and change something they shouldn't?

  • Use property but raise an exception if the instance variable is changed?

  • Something else?


Solution

  • Prepend name of the variable with __, and create read-only property, Python will take care of exceptions, and variable itself will be protected from accidental overwrite.

    class foo(object):
        def __init__(self, bar):
            self.__bar = bar
    
        @property
        def bar(self):
            return self.__bar
    
    f = foo('bar')
    f.bar         # => bar
    f.bar = 'baz' # AttributeError; would have to use f._foo__bar