[Tutor] How to write protect attributes or names

Alexandre Ratti alex at gabuzomeu.net
Thu Sep 18 15:25:35 EDT 2003

Hello Gregor,

Gregor Lingl wrote:
> Alexandre Ratti schrieb:
>> 2) You could also use properties (in Python 2.2+) to create read-only 
>> attributes:
> Hmmm..., interesting, but I want to write-protect methods, i.e. callable 
> attributes. That will not work with properties

This reminds me of this document I read a few weeks ago about the 
descriptor protocol:

	How-To Guide for Descriptors, Raymond Hettinger

I found it very interesting, though a bit complex. As I understand it, 
properties are a special case of descriptors. A descriptor is basically 
a go-between class that controls how you access an attribute or a method.

We could write a descriptor that wraps a normal method to prevent anyone 
from remapping (or deleting) its name. This is based on the last example 
in the "How-To Guide for Descriptors":

class Protector(object):

     def __init__(self, f):
         self.f = f

     def __set__(self, *args):
         print "Oh no. You cannot remap this method name."

     def __delete__(self, *args):
         print "Don't you even think of deleting this name!"

     def __get__(self, obj, cls = None):
         # When called from an instance,
         # obj = instance and cls = class.
         def f(*args):
             return self.f(obj, *args)
         return f

class Foo(object):

     def _doer(self, arg):
         """Simulates a method that does something."""
         return "toto: %s" % arg

     doer = Protector(_doer)

Let's try it:

 >>> f = Foo()
 >>> f.doer('titi')
'toto: titi'
 >>> f.doer(2)
'toto: 2'
 >>> f.doer = "new name"
Oh no. You cannot remap this method name.
 >>> del f.doer
Don't you even think of deleting this name!

Now you just need to find a way to automate the creation of the 
descriptor methods for every callable name that starts with a specific 
prefix. This example might be interesting:


Overriding "__setattr__" might be more straightforward, though.



More information about the Tutor mailing list