Constant instance variables?

I use the 'property' to ensure that changes to instances of object instances are wrapped by the methods I need.

How about when an instance has a variable that cannot be logically changed? For example, if I create a class for a Process, each instance of the Process should have a pid attribute that will be available often, but should not be changed.

What is the most Pythonic way to handle someone trying to change this instance variable?

  • Just trust the user to not try and change what they shouldn't?

  • Use a property, but an exception if the instance variable has changed?

  • Something else?

+6
python properties setter instance instance-variables
source share
4 answers

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

 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 
+6
source share

Simple user trust is not necessarily bad; if you just write a quick Python program that will be used once and thrown away, you may well just hope that the user does not change the pid field.

IMHO the most Pythonic way to force a read-only field is to use a property that throws an exception when trying to set a field.

So, IMHO, you have good instincts about it.

+3
source share

Perhaps you can override __setattr__ ? In line,

 def __setattr__(self, name, value): if self.__dict__.has_key(name): raise TypeError, 'value is read only' self.__dict__[name] = value 
+1
source share

Just use the property and the hidden attribute (with a single underscore prefix).

Simple properties are read-only!

 >>> class Test (object): ... @property ... def bar(self): ... return self._bar ... >>> t = Test() >>> t._bar = 2 >>> t.bar 2 >>> t.bar = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't set attribute 

Double underline hiding is not used to hide the implementation, but to make sure that you do not encounter subclass attributes; consider mixin, for example, it must be very careful!

If you just want to hide the attribute, use one underscore. And as you can see, there is no extra magic to add - if you do not define the set function, your property is as read-only as the return value of the method.

+1
source share

All Articles