Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
mikemaccana Avatar asked Oct 06 '09 18:10

mikemaccana


2 Answers

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
like image 90
Cat Plus Plus Avatar answered Sep 25 '22 06:09

Cat Plus Plus


Simply trusting the user is not necessarily a bad thing; if you are just writing a quick Python program to be used once and thrown away, you might very well just trust that the user not alter the pid field.

IMHO the most Pythonic way to enforce the read-only field is to use a property that raises an exception on an attempt to set the field.

So, IMHO you have good instincts about this stuff.

like image 33
steveha Avatar answered Sep 25 '22 06:09

steveha