[Python-Dev] RFC: readproperty

Steven Bethard steven.bethard at gmail.com
Wed Sep 28 18:04:42 CEST 2005


Jim Fulton wrote:
> A common use of read descriptors is for lazily computed data:
>
>    class readproperty(object):
>        "Create a read descriptor from a function"
>
>        def __init__(self, func):
>            self.func = func
>
>        def __get__(self, inst, class_):
>            if inst is None:
>                return self
>
>            return self.func(inst)
>
>    class Spam:
>
>        @readproperty
>        def eggs(self):
>            ... expensive computation of eggs
>
>            self.eggs = result
>            return result

I've also needed behavior like this a few times, but I use a variant
of Scott David Daniel's recipe[1]:

class _LazyAttribute(object):
    def __init__(self, calculate_function):
        self._calculate = calculate_function

    def __get__(self, obj, _=None):
        if obj is None:
            return self
        try:
            value = self._calculate(obj)
        except AttributeError, e:
            # I don't like this, but if _calculate raises an
            # AttributeError and I don't catch it, the descriptor
            # machinery hides it and I can't debug my code
            raise Exception(e)
        setattr(obj, self._calculate.func_name, value)
        return value

It uses the .func_name attribute to put the "self.eggs = result" into
the property.  I like that I don't have to do the set at the end of
every function, and I'm never doing anything complicated enough that I
don't want the attribute named the same as the function that I passed
in.

[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602

STeVe
--
You can wordify anything if you just verb it.
        --- Bucky Katt, Get Fuzzy


More information about the Python-Dev mailing list