|
3 | 3 | """ |
4 | 4 |
|
5 | 5 | # Standard library modules. |
6 | | -import weakref |
7 | 6 |
|
8 | 7 | # Third party modules. |
9 | 8 |
|
10 | 9 | # Local modules. |
11 | 10 |
|
12 | 11 | # Globals and constants variables. |
13 | 12 |
|
14 | | -class Immutable(type): |
15 | | - """ |
16 | | - Make a class immutable. |
17 | | - The attribute cannot be added or modified. |
18 | | - The attributes should be defined by the argument ``attrs`` in the class |
19 | | - definition:: |
20 | | - |
21 | | - class Foo(metaclass=Immutable, attrs=('bar',)): |
22 | | - pass |
23 | | - |
24 | | - The constructor of the class then takes the same number of arguments:: |
25 | | - |
26 | | - foo = Foo('abc') |
27 | | - foo.bar # returns 'abc' |
28 | | - """ |
29 | | - |
30 | | - def __new__(cls, name, bases, methods, *, attrs=None): |
31 | | - # Make a __new__ function and add to the class dict |
32 | | - def __new__(cls, *args, **kwargs): |
33 | | - args = list(args) |
34 | | - |
35 | | - for key, value in kwargs.items(): |
36 | | - try: |
37 | | - index = attrs.index(key) |
38 | | - except ValueError: |
39 | | - raise TypeError('Unknown argument: {0}'.format(key)) |
40 | | - args.insert(index, value) |
41 | | - |
42 | | - if len(args) != len(attrs): |
43 | | - raise TypeError('Expected {} arguments'.format(len(attrs))) |
44 | | - |
45 | | - obj = object.__new__(cls) |
46 | | - obj._values = tuple(args) |
47 | | - obj._attrs = tuple(attrs) |
48 | | - |
49 | | - return obj |
50 | | - methods['__new__'] = __new__ |
51 | | - |
52 | | - # Configure __slots__ |
53 | | - methods['__slots__'] = ('__weakref__', '_values', '_attrs') |
54 | | - |
55 | | - # Configure __hash__ |
56 | | - methods['__hash__'] = lambda s: hash((s.__class__, s._values)) |
57 | | - |
58 | | - # Configure copy |
59 | | - methods['__copy__'] = lambda s: s |
60 | | - methods['__deepcopy__'] = lambda s, memo: s |
61 | | - |
62 | | - # Configure pickle |
63 | | - methods['__getnewargs_ex__'] = lambda s: (s._values, {}) |
64 | | - |
65 | | - # Populate a dictionary of field property accessors |
66 | | - methods.update({name: property(lambda s, n=n: s._values[n]) |
67 | | - for n, name in enumerate(attrs)}) |
68 | | - |
69 | | - cls = super().__new__(cls, name, bases, methods) |
70 | | - |
71 | | - return cls |
72 | | - |
73 | | - def __init__(self, name, bases, methods, *, attrs=None): |
74 | | - super().__init__(name, bases, methods) |
75 | | - |
76 | | -class Cachable(type): |
77 | | - """ |
78 | | - From Beazley, D. & Jones, B. K. (2013) Python Cookbook, O'Reilly. |
79 | | - |
80 | | - Creates a cache using the arguments of :meth:`__init__`. |
81 | | - """ |
82 | | - |
83 | | - def __init__(self, name, bases, methods): |
84 | | - super().__init__(name, bases, methods) |
85 | | - self.__cache = weakref.WeakValueDictionary() |
86 | | - |
87 | | - def __call__(self, *args, **kwargs): |
88 | | - cachekey = args + tuple(sorted(kwargs.items())) |
89 | | - if cachekey in self.__cache: |
90 | | - return self.__cache[cachekey] |
91 | | - |
92 | | - # Create object |
93 | | - obj = super().__call__(*args, **kwargs) |
94 | | - |
95 | | - # Cached |
96 | | - self.__cache[cachekey] = obj |
97 | | - |
98 | | - return obj |
99 | | - |
100 | | -class Validable(type): |
101 | | - """ |
102 | | - Validates the object before it is created using the arguments from the |
103 | | - :meth:`__init__`. |
104 | | - The class method :meth:`validate` should be overwritten. |
105 | | - There are three options for the return values of the :meth:`validate`: |
106 | | - |
107 | | - 1. return ``None`` or no return at all: the same arguments and |
108 | | - keyword arguments are passed to the constructor |
109 | | - 2. return a :class:`tuple` and a :class:`dict`: the tuple contains |
110 | | - updated arguments and the dict, updated keyword-arguments |
111 | | - 3. return a :class:`tuple`: the tuple contains updated arguments. |
112 | | - No keyword-arguments is passed to the constructor. |
113 | | - |
114 | | - In all other cases, a :exc:`ValueError` is raised. |
115 | | - """ |
116 | | - |
117 | | - def validate(cls, *args, **kwargs): #@NoSelf #pragma: no cover |
118 | | - return args |
119 | | - |
120 | | - def __call__(self, *args, **kwargs): |
121 | | - out = self.validate(*args, **kwargs) |
122 | | - if out is not None: |
123 | | - if len(out) == 2 and \ |
124 | | - isinstance(out[0], tuple) and \ |
125 | | - isinstance(out[1], dict): |
126 | | - args, kwargs = out |
127 | | - elif isinstance(out, tuple): |
128 | | - args = out |
129 | | - kwargs = {} |
130 | | - else: #pragma: no cover |
131 | | - raise ValueError('Unknown type of return arguments') |
132 | | - |
133 | | - return super().__call__(*args, **kwargs) |
134 | | - |
135 | | -class Reprable(type): |
136 | | - """ |
137 | | - Construct the __repr__ of an object based on the :meth:`_repr_inner` method |
138 | | - if it is defined. |
139 | | - """ |
140 | | - |
141 | | - def __new__(cls, name, bases, methods, *args, **kwargs): |
142 | | - def __repr__(self): |
143 | | - s = '{0}('.format(self.__class__.__name__) |
144 | | - |
145 | | - if hasattr(self, '_repr_inner'): |
146 | | - s += self._repr_inner() |
147 | | - |
148 | | - else: |
149 | | - inner = [] |
150 | | - for attr, value in zip(self._attrs, self._values): |
151 | | - if hasattr(value, '_repr_inner'): |
152 | | - inner.append(value._repr_inner()) |
153 | | - elif '_' in attr: |
154 | | - _, unit = attr.rsplit('_', 1) |
155 | | - inner.append('{0:.4e}{1}'.format(value, unit)) |
156 | | - else: |
157 | | - inner.append('{0}={1}'.format(attr, value)) |
158 | | - s += ', '.join(inner) |
159 | | - |
160 | | - s += ')' |
161 | | - return s |
162 | | - methods['__repr__'] = __repr__ |
163 | | - |
164 | | - return super().__new__(cls, name, bases, methods, *args, **kwargs) |
165 | | - |
166 | 13 | class ProgressMixin: |
167 | 14 |
|
168 | 15 | def update(self, progress): |
|
0 commit comments