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 | class CachedAttribute(object):
'''Computes attribute value and caches it in instance.
Example:
class MyClass(object):
def myMethod(self):
# ...
myMethod = CachedAttribute(myMethod)
Use "del inst.myMethod" to clear cache.'''
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
def __get__(self, inst, cls):
if inst is None:
return self
result = self.method(inst)
setattr(inst, self.name, result)
return result
class CachedClassAttribute(object):
'''Computes attribute value and caches it in class.
Example:
class MyClass(object):
def myMethod(cls):
# ...
myMethod = CachedClassAttribute(myMethod)
Use "del MyClass.myMethod" to clear cache.'''
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
def __get__(self, inst, cls):
result = self.method(cls)
setattr(cls, self.name, result)
return result
class ReadAliasAttribute(object):
'''If not explcitly assigned this attribute is an alias for other.
Example:
class Document(object):
title='?'
shortTitle=ReadAliasAttribute('title')'''
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
if inst is None:
return self
return getattr(inst, self.name)
class AliasAttribute(ReadAliasAttribute):
'''This attribute is an alias for other.
Example:
class Document(object):
newAttrName=somevalue
deprecatedAttrName=AliasAttribute('newAttrName')'''
def __set__(self, inst, value):
setattr(inst, self.name, value)
def __delete__(self, inst):
delattr(inst, self.name)
|