~divmod-dev/divmod.org/trunk

« back to all changes in this revision

Viewing changes to Epsilon/epsilon/remember.py

  • Committer: Jean-Paul Calderone
  • Date: 2014-06-29 20:33:04 UTC
  • mfrom: (2749.1.1 remove-epsilon-1325289)
  • Revision ID: exarkun@twistedmatrix.com-20140629203304-gdkmbwl1suei4m97
mergeĀ lp:~exarkun/divmod.org/remove-epsilon-1325289

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- test-case-name: epsilon.test.test_remember -*-
2
 
 
3
 
"""
4
 
This module implements a utility for managing the lifecycle of attributes
5
 
related to a particular object.
6
 
"""
7
 
 
8
 
from epsilon.structlike import record
9
 
 
10
 
class remembered(record('creationFunction')):
11
 
    """
12
 
    This descriptor decorator is applied to a function to create an attribute
13
 
    which will be created on-demand, but remembered for the lifetime of the
14
 
    instance to which it is attached.  Subsequent accesses of the attribute
15
 
    will return the remembered value.
16
 
 
17
 
    @ivar creationFunction: the decorated function, to be called to create the
18
 
        value.  This should be a 1-argument callable, that takes only a 'self'
19
 
        parameter, like a method.
20
 
    """
21
 
 
22
 
    value = None
23
 
 
24
 
    def __get__(self, oself, type):
25
 
        """
26
 
        Retrieve the value if already cached, otherwise, call the
27
 
        C{creationFunction} to create it.
28
 
        """
29
 
        remembername = "_remembered_" + self.creationFunction.func_name
30
 
        rememberedval = oself.__dict__.get(remembername, None)
31
 
        if rememberedval is not None:
32
 
            return rememberedval
33
 
        rememberme = self.creationFunction(oself)
34
 
        oself.__dict__[remembername] = rememberme
35
 
        return rememberme
36
 
 
37
 
 
38
 
 
39
 
__all__ = ['remembered']