2023-10-18_python-descriptors-part-2.html


001| #:name::Python Descriptors, part 2
002| #:link::https://thehardcorecoder.com/2023/10/18/python-descriptors-part-2/
003| #:date::2023-10-18
004| #:code::
005| class myDescriptor:
006|     '''Non-descript Descriptor class.'''
007| 
008|     def __get__ (self, obj, cls):
009|         which = 'object' if obj else 'class'
010|         print('%s.get()' % which)
011|         return None
012| 
013|     def __set__ (self, obj, val):
014|         print('set(%s)' % val)
015| 
016|     def __delete__ (self, obj):
017|         print('Nope!')
018| 
019| class myClass:
020|     x = myDescriptor()
021|     y = myDescriptor()
022| 
023| my_instance = myClass()
024| print(my_instance.x, my_instance.y)
025| print()
026| 
027| my_instance.x = 42
028| my_instance.y = 21
029| print(my_instance.x, my_instance.y)
030| print()
031| 
032| del my_instance.x
033| del my_instance.y
034| 
035| #:code::
036| class DependentProperty:
037|     '''Dependent property knows about the class that uses it.'''
038| 
039|     def __init__ (self, default=(0,0)):
040|         '''New instance.'''
041|         self.default = default
042| 
043|     def __get__ (self, obj, cls):
044|         '''Get property value.'''
045|         if obj:
046|             return (obj._x, obj._y)
047|         return self.default
048| 
049|     def __set__ (self, obj, value):
050|         '''Set property value.'''
051|         obj._x = value[0]
052|         obj._y = value[1]
053| 
054|     def __delete__ (self, obj):
055|         '''Reset Property to default.'''
056|         obj._x = self.default[0]
057|         obj._y = self.default[1]
058| 
059| class DependentPropertyExample (PointBaseClass):
060|     xy = DependentProperty((-1,-1))
061| 
062| 
063| obj = DependentPropertyExample(21, 42)
064| print(DependentPropertyExample.xy, '\n')
065| print('obj: %s' % obj)
066| print('obj.xy=(%d,%d)' % obj.xy)
067| print('obj._x=%s obj._y=%s\n' % (obj._x, obj._y))
068| 
069| obj.xy = (86, 99)
070| print('obj.xy=(%d,%d)\n' % obj.xy)
071| 
072| del obj.xy
073| print('obj.xy=(%d,%d)' % obj.xy)
074| 
075| #:code::
076| class ConfiguredProperty:
077|     '''Descriptor class for configurable attributes.'''
078|     modes = ['','str','hex','oct','bin','float','cmplx','raw']
079| 
080|     def __init__ (self, data, mode='str'):
081|         if mode not in ConfiguredProperty.modes:
082|             raise ValueError('Illegal mode: "%s"' % mode)
083| 
084|         self._data = data
085|         self._mode = mode.lower()
086| 
087|     def __get__ (self, obj, cls):
088|         if obj is None:
089|             return self._mode
090| 
091|         if self._mode == 'str': return str(self._data)
092|         if self._mode == 'hex': return ('%x' % self._data)
093|         if self._mode == 'oct': return ('%o' % self._data)
094|         if self._mode == 'bin': return ('%s' % bin(self._data)[2:])
095|         if self._mode == 'oct': return ('%o' % self._data)
096| 
097|         if self._mode == 'float':
098|             return ('%.6f' % self._data)
099| 
100|         if self._mode == 'cmplx':
101|             z = self._data
102|             return ('[%+6.3f, %+6.3fi]' % (z.real, z.imag))
103| 
104|         # Return raw data...
105|         return self._data
106| 
107|     def __set__ (self, obj, value):
108|         if value not in ConfiguredProperty.modes:
109|             raise ValueError('Illegal mode: "%s"' % value)
110| 
111|         # Set mode to a (valid!) new value...
112|         self._mode = value
113| 
114|     def __delete__ (self, obj):
115|         # Set mode to default...
116|         self._mode = 'str'
117| 
118| class ConfiguredPropertyExample:
119|     '''Class using configured attributes.'''
120| 
121|     a = ConfiguredProperty(21, mode='hex')
122|     b = ConfiguredProperty('local')
123|     c = ConfiguredProperty(3.14159, mode='float')
124|     d = ConfiguredProperty(complex(1,1), mode='cmplx')
125| 
126| 
127| sq = lambda x: ('"%s"' % x) if isinstance(x,str) else x
128| obj = ConfiguredPropertyExample()
129| 
130| print('a:%s = %s' % (ConfiguredPropertyExample.a, sq(obj.a)))
131| print('b:%s = %s' % (ConfiguredPropertyExample.b, sq(obj.b)))
132| print('c:%s = %s' % (ConfiguredPropertyExample.c, sq(obj.c)))
133| print('d:%s = %s' % (ConfiguredPropertyExample.d, sq(obj.d)))
134| print()
135| 
136| fmt = 'a:%s = %s'
137| obj.a = 'raw'
138| print(fmt % (ConfiguredPropertyExample.a, sq(obj.a)))
139| obj.a = 'bin'
140| print(fmt % (ConfiguredPropertyExample.a, sq(obj.a)))
141| obj.a = 'hex'
142| print(fmt % (ConfiguredPropertyExample.a, sq(obj.a)))
143| obj.a = 'float'
144| print(fmt % (ConfiguredPropertyExample.a, sq(obj.a)))
145| print()
146| 
147| del obj.a
148| print(fmt % (ConfiguredPropertyExample.a, sq(obj.a)))
149| obj.a = 'hex'
150| print(fmt % (ConfiguredPropertyExample.a, sq(obj.a)))
151| print()
152| 
153| #:code::
154| class SimpleProperty:
155|     '''Simple property descriptor.'''
156| 
157|     def __init__ (self, default):
158|         self.name = '<new>'
159|         self.default = default
160| 
161|     def __str__ (self):
162|         return '(%s: %s)' % (self.name, self.default)
163| 
164|     def __set_name__ (self, owner, name):
165|         '''Set attribute name.'''
166|         self.name = '_%s' % name
167| 
168|     def __get__ (self, obj, owner):
169|         '''Get attribute value (or name).'''
170|         return obj.__dict__[self.name] if obj else self.default
171| 
172|     def __set__ (self, obj, value):
173|         '''Set attribute value.'''
174|         obj.__dict__[self.name] = value
175| 
176|     def __delete__ (self, obj):
177|         '''Reset attribute value.'''
178|         obj.__dict__[self.name] = self.default
179| 
180| 
181| class SimplePropertyExample:
182|     p1 = SimpleProperty(42)
183|     p2 = SimpleProperty(6.28318)
184|     p3 = SimpleProperty('user')
185|     p4 = SimpleProperty('/info')
186| 
187|     def __init__ (self, name, p1=None, p2=None, p3=None, p4=None):
188|         self.name = name
189|         self._p1 = SimplePropertyExample.p1 if p1 is None else p1
190|         self._p2 = SimplePropertyExample.p2 if p2 is None else p2
191|         self._p3 = SimplePropertyExample.p3 if p3 is None else p3
192|         self._p4 = SimplePropertyExample.p4 if p4 is None else p4
193| 
194|     def __str__ (self):
195|         return ('%s:%s' % (self.name, self.__class__.__name__))
196| 
197|     def __repr__ (self):
198|         return '{%s @%012x}' % (self.__class__.__name__, id(self))
199| 
200| 
201| print('=== class:%s (default) values ===' % SimplePropertyExample.__name__)
202| print('p1=',SimplePropertyExample.p1)
203| print('p2=',SimplePropertyExample.p2)
204| print('p3=',SimplePropertyExample.p3)
205| print('p4=',SimplePropertyExample.p4, '\n')
206| 
207| b1 = SimplePropertyExample('pooh', 68, 2.71828)
208| print('=== Object %s values ===' % b1)
209| print('p1=',b1.p1)
210| print('p2=',b1.p2)
211| print('p3=',b1.p3)
212| print('p4=',b1.p4, '\n')
213| 
214| b2 = SimplePropertyExample('bear', 86, 42.21, 'root', '/debug')
215| print('=== Object %s values ===' % b2)
216| print('p1=',b2.p1)
217| print('p2=',b2.p2)
218| print('p3=',b2.p3)
219| print('p4=',b2.p4, '\n')
220| 
221| print('Set b1 properties...')
222| b1.p1 = 3.14159
223| b1.p2 = 99
224| b1.p3 = 'piglet'
225| b1.p4 = complex(0, 1)
226| print('=== %s values ===' % b1)
227| print('p1=',b1.p1)
228| print('p2=',b1.p2)
229| print('p3=',b1.p3)
230| print('p4=',b1.p4, '\n')
231| 
232| print('Copy default properties to b2...')
233| b2.p1 = SimplePropertyExample.p1
234| b2.p2 = SimplePropertyExample.p2
235| b2.p3 = SimplePropertyExample.p3
236| b2.p4 = SimplePropertyExample.p4
237| print('=== %s values ===' % b2)
238| print('p1=',b2.p1)
239| print('p2=',b2.p2)
240| print('p3=',b2.p3)
241| print('p4=',b2.p4, '\n')
242| 
243| print('Delete b1 properties...')
244| del b1.p1
245| del b1.p2
246| del b1.p3
247| del b1.p4
248| print('=== %s values ===' % b1)
249| print('p1=',b1.p1)
250| print('p2=',b1.p2)
251| print('p3=',b1.p3)
252| print('p4=',b1.p4, '\n')
253| 
254| #:code::
255| typename = lambda obj: type(obj).__name__
256| 
257| class InstrumentedProperty:
258|     '''Instrumented property class.'''
259| 
260|     def __init__ (self, config=(-100,+100)):
261|         '''New InstrumentedProperty property.'''
262|         t = (typename(self), id(self), config)
263|         print('{%s @%012x} init: %s' % t)
264| 
265|         # Initialize instance...
266|         self.name = '{new}'
267|         self.config = config
268| 
269|     def __set_name__ (self, owner, name):
270|         '''Set Property name.'''
271|         t = (typename(self), id(self), name, owner.__name__, id(owner))
272|         print('{%s @%012x} set-name: %s on {%s @%012x}' % t)
273| 
274|         # Set property name...
275|         self.name = '_%s' % name
276| 
277|     def __set__ (self, obj, value):
278|         '''Set Property value. Sets property configuration'''
279|         t = (typename(self), id(self), value, typename(obj), id(obj))
280|         print('{%s @%012x} set: %s {%s @%012x}' % t)
281| 
282|         # Check if the value is in range...
283|         if self.config[0] <= value <= self.config[1]:
284|             obj.__dict__[self.name] = value
285|             return
286| 
287|         # Error, not in range...
288|         raise ValueError('Invalid value for %s: %s' % (self.name,value))
289| 
290|     def __get__ (self, obj, cls):
291|         '''Get Property value.'''
292|         caller = '{null}' if obj is None else ('{%s @%012x}' % (typename(obj), id(obj)))
293|         t = (typename(self), id(self), caller, cls.__name__, id(cls))
294|         print('{%s @%012x} get: %s{%s @%012x}' % t)
295| 
296|         # If called on instance, return the parameter value...
297|         if obj:
298|             return obj.__dict__[self.name]
299| 
300|         # Otherwise called on class, return the configuration...
301|         return self.config
302| 
303|     def __delete__ (self, obj):
304|         '''Reset Property return mode to default.'''
305|         t = (typename(self), id(self), typename(obj), id(obj))
306|         print('{%s @%012x} delete: {%s @%012x}' % t)
307| 
308|         # Reset the value to zero...
309|         obj.__dict__[self.name] = 0
310| 
311|     def __str__ (self):
312|         '''Return a nice string version.'''
313|         return '%s: {%s}' % (typename(self), self.config)
314| 
315| 
316| class InstrumentedPropertyExample:
317|     x = InstrumentedProperty()
318|     y = InstrumentedProperty()
319| 
320|     def __init__ (self, x=0, y=0):
321|         self._x = x
322|         self._y = y
323| 
324|     def __call__ (self): return (self.x, self.y)
325|     def __str__ (self): return '(%s, %s)' % (self.x, self.y)
326|     def __repr__ (self): return '{%s @%012x}' % (typename(self), id(self))
327| 
328| 
329| p0 = InstrumentedPropertyExample()
330| p1 = InstrumentedPropertyExample(21, 42)
331| p2 = InstrumentedPropertyExample(-1, -1)
332| print()
333| print('Property configurations')
334| print(InstrumentedPropertyExample.x)
335| print(InstrumentedPropertyExample.y, '\n')
336| print('Initialized:')
337| print('%s %s %s\n' % (p0, p1, p2))
338| try: p1.x = 200
339| except Exception as e:
340|     print('ERR:', e, '\n')
341| p1.x = +99
342| p1.y = -99
343| p2.x = +100
344| p2.y = -100
345| print('%5s %5s %5s\n' % (p0, p1, p2))
346| 
347| print('del p2 .x and .y:')
348| del p2.x
349| del p2.y
350| print('%5s %5s %5s\n' % (p0, p1, p2))
351| 
352| #:end:code::
353|