Thursday, 13 October 2011

Python Descriptors and Properties


Descriptor example
class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print 'Retrieving', self.name
        return self.val

    def __set__(self, obj, val):
        print 'Updating' , self.name
        self.val = val

>>> class MyClass(object):
    x = RevealAccess(10, 'var "x"')
    y = 5

>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5
Or there is a property keyword for fast access, the string passed in doc will be accessible as self.[property].__doc__ within the get,set methods:
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

## where an equivalent would be:
class property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self         
        if self.fget is None:
            raise AttributeError, "unreadable attribute"
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError, "can't set attribute"
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError, "can't delete attribute"
        self.fdel(obj)
It allows some curious class methods behaviour:
class Cell(object):
    . . .
    def getvalue(self, obj):
        "Recalculate cell before returning value"
        self.recalc()
        return obj._value
    value = property(getvalue)
And my recipe of usage would be:
def fget(self,var):
    return getattr(self,var)
def fset(self,value,var):
    setattr(self,var,value)
def fdel(self,var):
    delattr(self,var)
def make_property(fget,fset,doc):
    return property(partial(fget,var=doc),partial(fset,var=doc),partial(fdel,var=doc),doc=doc)

MyObject.X = make_property(fget,fset,fdel,'X')


No comments:

Post a Comment