File: props.py

package info (click to toggle)
genometools 1.6.1%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 50,412 kB
  • sloc: ansic: 271,241; ruby: 30,339; python: 4,880; sh: 3,193; makefile: 1,194; perl: 219; pascal: 159; haskell: 37; sed: 5
file content (112 lines) | stat: -rw-r--r-- 2,238 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python
# -*- coding: utf-8 -*-


class cachedproperty(object):

    '''
    >>> class C(object):
    ...    def __init__(self, x):
    ...        self._x = x
    ...    def get_x(self):
    ...        print "getting x"
    ...        return self._x
    ...
    ...    def set_x(self, newx):
    ...        print "setting x with %s" % newx
    ...        self._x = newx
    ...    def del_x(self):
    ...        self._x = "i am deleted"
    ...
    ...    x = cachedproperty(get_x, set_x, del_x)
    ...    other_x = cachedproperty(get_x, set_x)

    >>> c = C(5)
    >>> c.x
    getting x
    5

    # cached.
    >>> c.x
    5

    >>> c.x, c.y = 6, 7
    setting x with 6

    # uncached.
    >>> c.x
    getting x
    6

    >>> c.x, c.y
    (6, 7)

    >>> c.y = 35
    >>> c.x, c.y
    (6, 35)

    # ok with multiple instances.
    >>> d = C(4)
    >>> d.x
    getting x
    4

    >>> c.x
    6
    >>> c.other_x = 7
    setting x with 7

    >>> c.get_x()
    getting x
    7
    >>> del c.x
    >>> c.x
    getting x
    \'i am deleted\'

    >>> c.set_x(22)
    setting x with 22

    # but the property cant know about it...
    >>> c.x
    \'i am deleted\'


    '''

    __slots__ = ("fget", "fset", "fdel", "n")

    def __init__(self, fget=None, fset=None, fdel=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.n = "__" + fget.__name__

    def __get__(self, o, otype=None):
        if o is None:
            return None
        if self.n in o.__dict__:
            return (o.__dict__)[self.n]
        result = (o.__dict__)[self.n] = self.fget(o)
        return result

    def __set__(self, o, value):
        if self.fset is None:
            raise AttributeError("unsettable %s (with %s)" % (self.n, value))
        else:
            if self.n in o.__dict__:
                del (o.__dict__)[self.n]
            self.fset(o, value)

    def __delete__(self, o):
        if self.fdel is None:
            raise AttributeError("undeletable %s (with %s)" % (self.n, value))
        else:
            if self.n in o.__dict__:
                del (o.__dict__)[self.n]
            self.fdel(o)


if __name__ == "__main__":
    import doctest
    doctest.testmod()