A python classproperty

In rare occassions I need a property on a classmethod. Until now I've only needed getter-access (setting properties on classes dynamically is scary anyway). Here's my implementation:

def classproperty(f):
    """
        E.g.
        >>> class foo(object):
        ...    @classproperty
        ...    def name(cls):
        ...        return cls.__name__
        >>> print foo.name 
        'foo'
    """
    class cpf(object):
        def __init__(self, getter):  
            self.getter = getter

        def __get__(self, obj, type=None):
            return self.getter(type)
    return cpf(f)

.. but if you need to you can of course implement the missing descriptor methods yourself.

Last updated April 18, 2013, 4:35 p.m. | filed under python | descriptors properties classproperty
comments powered by Disqus