-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheasy_property.py
91 lines (79 loc) · 2.4 KB
/
easy_property.py
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
"""
easy_property.py
with easy_property it possible to define properties with the decorators
- getter
- setter
- deleter
- getter_setter
,instead of the property decorator.
E.g. instead of
Class Demo:
def __init__(self, val):
self.a = val
@property
def a(self):
return self._a
@a.setter
def a(self, val):
self._a = val
, you can now write
Class Demo:
def __init__(self, val):
self.a = val
@getter
def a(self):
return self._a
@setter
def a(self, val):
self._a = val
, or even
Class Demo:
def __init__(self, val):
self.a = val
@getter_setter
def a(self, val=None):
if val is None:
return self._a
self._a = val
Likewise, @deleter can be used to specify deleter.
And unlike @property, it is possible to define the docstring with the @documenter decorator:
Class Demo:
def __init__(self, val):
self.a = val
@getter
def a(self):
return self._a
@setter
def a(self, val):
self._a = val
@descriptor
def a(self): # this should be method returning the required docstring
return 'This is the descriptor of Demo.a'
In contrast to an ordinary @property decorator, the order in which the getter, setter, deleter and documenter
appear is not relevant.
So:
Class Demo:
def __init__(self, val):
self.a = val
@setter
def a(self, val):
self._a = val
@getter
def a(self):
return self._a
, is perfectly valid.
"""
import functools
__version__ = "0.0.5"
def action(f, frefs):
if f.__qualname__ == action.qualname:
if any(action.f[fref] is not None for fref in frefs.split("_")):
raise AttributeError(f"decorator defined twice")
else:
action.f.update({}.fromkeys(action.f, None)) # reset all values to None
action.qualname = f.__qualname__
action.f.update({}.fromkeys(frefs.split("_"), f(0) if frefs == "documenter" else f)) # set all frefs values to f
return property(*(action.f[ref] for ref in action.f))
action.qualname = None
action.f = dict.fromkeys(["getter", "setter", "deleter", "documenter"], None)
globals().update({fref: functools.partial(action, frefs=fref) for fref in {**action.f, "getter_setter": None}})