On Mar 28, 2012, at 9:37 AM, Michael Bayer wrote:
>
>
> class memoized_property(object):
> """A read-only @property that is only evaluated once."""
> def __init__(self, fget, doc=None):
> self.fget = fget
> self.__doc__ = doc or fget.__doc__
> self.__name__ = fget.__name__
>
> def __get__(self, obj, cls):
> if obj is None:
> return self
> obj.__dict__[self.__name__] = result = self.fget(obj)
> return result
thinking a little further, here's an ORMish way to use it:
def invalidates(source, *attr):
@event.listens_for(source, 'set')
def invalidate(target, value, old, initiator):
for attr_ in attr:
target.__dict__.pop(attr_, None)
class MyClass(Base):
__tablename__ = 'mytable'
id = Column(Integer, primary_key=True)
a = Column(Integer)
b = Column(Integer)
@memoized_property
def c(self):
print "evaluating a + b"
return self.a + self.b
invalidates(MyClass.a, 'c')
invalidates(MyClass.b, 'c')
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.