[Tutor] How to write protect attributes or names

Alexandre Ratti alex at gabuzomeu.net
Tue Sep 16 13:58:12 EDT 2003


Hi Gregor,


Gregor Lingl wrote:
> is it possible to "write-protect" a definitive selection of attributes
> (a) of a class
> (b) of an object
> (c) or a definitve selection of names of a module?
> e.g. all the callable ones.

For a class:

1) You could prefix your attribute names with two underscores so that 
they cannot be (easily) accessed from outside of the class because of 
the name-mangling feature. Example:

##
 >>> class Foo(object):
... 	def __init__(self):
... 		self.__bar = "titi"
... 	def test(self):
... 		print self.__bar
... 		

 >>> f = Foo()
 >>> f.test()
titi
 >>> f.__bar
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'Foo' object has no attribute '__bar'
 >>> print [x for x in dir(f) if "bar" in x]
['_Foo__bar']
##

The attribute name is automatically modified so that it cannot be easily 
modified.

2) You could also use properties (in Python 2.2+) to create read-only 
attributes:

##
 >>> class Foo(object):
... 	def __init__(self):
... 		self._bar = "toto"
... 	def getBar(self):
... 		return self._bar
... 	bar = property(getBar)
... 	
 >>> f = Foo()
 >>> print f.bar
toto
 >>> f.bar = "titi"
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: can't set attribute
##

If you do not create a mathod to set the attribute value and pass it in 
the property() call, then the attribute will be read-only.

You could also try to override the "__setattr__" method in your class to 
disallow settng specific attributes.

I'm not sure what you can do at the module level.


HTH.

Alexandre







More information about the Tutor mailing list