Read-only class properties

George Sakkis gsakkis at rutgers.edu
Sun Jul 10 16:38:22 EDT 2005


I'm trying to write a decorator similar to property, with the
difference that it applies to the defining class (and its subclasses)
instead of its instances. This would provide, among others, a way to
define the equivalent of class-level constants:

class Foo(object):
    @classproperty
    def TheAnswer(cls):
        return "The Answer according to %s is 42" % cls.__name__

>>> Foo.TheAnswer
The Answer according to Foo is 42
>> Foo.TheAnswer = 0
exceptions.AttributeError
...
AttributeError: can't set class attribute

I read the 'How-To Guide for Descriptors'
(http://users.rcn.com/python/download/Descriptor.htm) that describes
the equivalent python implementation of property() and classmethod()
and I came up with this:

def classproperty(function):
    class Descriptor(object):
        def __get__(self, obj, objtype):
           return function(objtype)
        def __set__(self, obj, value):
            raise AttributeError, "can't set class attribute"
    return Descriptor()

Accessing Foo.TheAnswer works as expected, however __set__ is
apparently not called because no exception is thrown when setting
Foo.TheAnswer. What am I missing here ?

George




More information about the Python-list mailing list