2025-10-13_python-decorators-redux.html
001|
002|
003|
004|
005| def FunctionDecorator (function):
006| '''Decorator function for a function.'''
007|
008| def wrapper (*args, **kwargs):
009| '''Wrapper function -- wraps the decorated function.'''
010|
011|
012| return function(*args, **kwargs)
013|
014|
015| return wrapper
016|
017|
018| def MethodDecorator (method):
019| '''Decorator function for a class method.'''
020|
021| def wrapper (self, *args, **kwargs):
022| '''Wrapper function -- wraps the decorated method.'''
023|
024|
025| return method(self, *args, **kwargs)
026|
027|
028| return wrapper
029|
030|
031| def ClassDecorator (klass):
032| '''Decorator function for a class.'''
033|
034| def wrapper (*args, **kwargs):
035| '''Wrapper function -- wraps the decorated class.'''
036|
037|
038| return klass(*args, **kwargs)
039|
040|
041| return wrapper
042|
043|
044| import examples as eg
045|
046| @eg.ClassDecorator
047| class demo_class:
048| '''Demo class.'''
049|
050| @eg.MethodDecorator
051| def __init__ (self, a, b, c=None):
052| '''Demo instance method #1.'''
053| self.a = a
054| self.b = b
055| self.c = 0 if c is None else c
056|
057| @eg.MethodDecorator
058| def reset (self, a=None, b=None, c=None):
059| '''Demo instance method #2.'''
060| self.a = 0 if a is None else a
061| self.b = 0 if b is None else b
062| self.c = 0 if c is None else c
063|
064| @eg.MethodDecorator
065| def __str__ (self):
066| '''Demo instance method #3.'''
067| return f'[{self.a}, {self.b}, {self.c}]'
068|
069| @eg.FunctionDecorator
070| def function_1 (a, b, c, d):
071| '''Demo function #1.'''
072| return a+b+c+d
073|
074| @eg.FunctionDecorator
075| def function_2 (a, b, c=0, d=0):
076| '''Demo function #2.'''
077| return a-b-c-d
078|
079| @eg.FunctionDecorator
080| def function_3 (a=1, b=2, c=0, d=0):
081| '''Demo function #3.'''
082| return a*b*c*d
083|
084| if __name__ == '__main__':
085| obj1 = demo_class(21, 42, 63)
086| obj2 = demo_class(86, 99)
087| print(obj1, obj2, '', sep='\n')
088|
089| rv1 = function_1(21, 42, 63, 84)
090| rv2 = function_2(12, 24, 36, 48)
091| rv3 = function_3(99, 88, 77, 66)
092| print(rv1, rv2, rv3, '', sep='\n')
093|
094|
095| def BasicFunctionDecorator (function):
096| '''Basic template for a function decorator.'''
097|
098|
099| ftn_name = function.__qualname__
100| ftn_type = function.__class__.__name__
101| print(f'@Decorator: {ftn_name} ({ftn_type})')
102|
103| def wrapper (*args, **kwargs):
104| '''Wrapper function -- wraps the decorated function.'''
105| print(f'@[{ftn_name}]: {args} {kwargs}')
106| wrapper.count += 1
107|
108|
109| return function(*args, **kwargs)
110|
111|
112| wrapper.count = 0
113| return wrapper
114|
115|
116| from examples import BasicFunctionDecorator
117|
118| @BasicFunctionDecorator
119| def function_1 (a, b, c, d):
120| '''Demo function #1.'''
121| return a+b+c+d
122|
123| @BasicFunctionDecorator
124| def function_2 (a, b, c=0, d=0):
125| '''Demo function #2.'''
126| return a-b-c-d
127|
128| @BasicFunctionDecorator
129| def function_3 (a=1, b=2, c=0, d=0):
130| '''Demo function #3.'''
131| return a*b*c*d
132|
133| if __name__ == '__main__':
134|
135|
136| function_1(99, 86, 57, 68)
137| function_1(21, 42, -1, -1)
138| function_1(a=21, b=42, c=-1, d=-1)
139| function_1(99, 86, d=57, c=68)
140| print()
141|
142|
143| function_2(99, 86, 57, 68)
144| function_2(21, 42)
145| function_2(a=21, b=42)
146| function_2(99, 86, d=57, c=68)
147| print()
148|
149|
150| function_3(99, 86, 57, 68)
151| function_3(21, 42)
152| function_3(a=21, b=42)
153| print()
154| print()
155|
156|
157| print(f'function_1: {function_1.count} calls')
158| print(f'function_2: {function_2.count} calls')
159| print(f'function_3: {function_3.count} calls')
160| print()
161|
162|
163| def BasicMethodDecorator (method):
164| '''Basic template for a class method decorator.'''
165|
166|
167| ftn_name = method.__qualname__
168| cls_name = method.__class__.__name__
169| print(f'@MethodDecorator: {ftn_name} ({cls_name})')
170|
171| def wrapper (self, *args, **kwargs):
172| '''Wrapper function -- wraps the decorated method.'''
173| if not hasattr(self, 'log'):
174| setattr(self, 'log', [])
175|
176|
177| self.log.append(f'@[{ftn_name}]: {args} {kwargs}')
178|
179|
180| return method(self, *args, **kwargs)
181|
182|
183| return wrapper
184|
185|
186| from examples import BasicMethodDecorator
187|
188| class point:
189| '''Simple 2D X-Y point class.'''
190|
191| def __init__ (self, x=0.0, y=0.0):
192| '''New point instance. Default is (0,0)'''
193| self.x = float(x)
194| self.y = float(y)
195|
196| def __repr__ (self):
197| return f'[{self.x:.3f} x {self.y:.3f}]'
198|
199| @BasicMethodDecorator
200| def moveto (self, x, y):
201| '''Move point method.'''
202| self.x = float(x)
203| self.y = float(y)
204| return self
205|
206| @BasicMethodDecorator
207| def reset (self):
208| '''Reset point. Sets point to (0,0).'''
209| self.x = 0.0
210| self.y = 0.0
211| return self
212|
213| @property
214| @BasicMethodDecorator
215| def magnitude (self):
216| '''Point (vector) magnitude.'''
217| return pow(pow(self.x,2)+pow(self.y,2), 1/2)
218|
219| @BasicMethodDecorator
220| def diff (self, other):
221| '''Difference between two points.'''
222| return (abs(self.x - other.x), abs(self.y - other.y))
223|
224| @BasicMethodDecorator
225| def dot (self, other):
226| '''Return dot product of two points.'''
227| return (self.x * other.x) + (self.y * other.y)
228|
229| if __name__ == '__main__':
230| print()
231| pnt1 = point()
232| pnt2 = point(1, 1)
233|
234| pnt1.moveto(+2.71828, +3.14159)
235| pnt2.moveto(-6.62607, -0.510_998_950)
236| print()
237|
238|
239| print(f'{pnt1=}')
240| print(f'{pnt1.magnitude=}')
241| print(f'{pnt1.dot(pnt1)=}')
242| print(f'{pnt1.dot(pnt2)=}')
243| print(f'{pnt1.diff(pnt2)=}')
244| print()
245|
246|
247| print(f'{pnt2=}')
248| print(f'{pnt2.magnitude=}')
249| print(f'{pnt2.dot(pnt1)=}')
250| print(f'{pnt2.dot(pnt2)=}')
251| print(f'{pnt2.diff(pnt1)=}')
252| print()
253|
254|
255| for ix,line in enumerate(pnt1.log, start=1):
256| print(f'{ix:02d}: {line}')
257| print()
258|
259|
260| for ix,line in enumerate(pnt2.log, start=1):
261| print(f'{ix:02d}: {line}')
262| print()
263|
264|
265| def BasicClassDecorator (klass):
266| '''Basic template for a class decorator.'''
267|
268|
269| cls_name = klass.__qualname__
270| top_name = klass.__class__.__name__
271| print(f'@ClassDecorator: {cls_name} ({top_name})')
272|
273| def wrapper (*args, **kwargs):
274| '''Wrapper function -- wraps the decorated class.'''
275|
276|
277| wrapper.log.append(f'@[{cls_name}]: {args} {kwargs}')
278| wrapper.counter += 1
279|
280|
281| return klass(*args, **kwargs)
282|
283|
284| wrapper.log = []
285| wrapper.counter = 0
286|
287|
288| return wrapper
289|
290|
291| from examples import BasicClassDecorator
292|
293| @BasicClassDecorator
294| class beer:
295| '''Demo class.'''
296|
297| def __init__ (self, company, name, abv=0.0, ibu=0.0):
298| '''New beer instance.'''
299| self.name = name
300| self.company = company
301| self._abv = abv
302| self._ibu = ibu
303|
304| def __str__ (self):
305| return f'Yum! {self.company} {self.name} ({self.abv}/{self.ibu})'
306|
307| @property
308| def abv (self): return self._abv
309|
310| @property
311| def ibu (self): return self._ibu
312|
313| if __name__ == '__main__':
314|
315|
316| b0 = beer('Newcastle', 'Brown Ale', abv=4.7, ibu=18)
317| b1 = beer('New Belgium', 'Fat Tire', abv=5.2, ibu=15)
318| b2 = beer('New Belgium', 'Voodoo Ranger', abv=7.0, ibu=50)
319| b3 = beer('Stone', 'IPA', abv=6.9, ibu=71)
320| print()
321|
322|
323| print(b0)
324| print(b1)
325| print(b2)
326| print(b3)
327| print()
328|
329|
330| for ix,line in enumerate(beer.log):
331| print(f'{ix:2d}: {line}')
332| print()
333|
334|
335| from examples import BasicClassDecorator
336|
337| @BasicClassDecorator
338| class chessboard:
339| '''Demo class with class variables.'''
340| Rows = 8
341| Cols = 8
342|
343| def __init__ (self):
344| '''New chessboard instance.'''
345| self.board = [[0 for col in range(chessboard.Cols)]
346| for row in range(chessboard.Rows)]
347|
348| if __name__ == '__main__':
349| print()
350|
351|
352| brd = chessboard()
353| print(brd)
354| print()
355|
356|
357| from examples import BasicClassDecorator
358|
359| @BasicClassDecorator
360| class chessboard:
361| '''Demo class with class variables.'''
362| Rows = 8
363| Cols = 8
364|
365| def __init__ (self):
366| '''New chessboard instance.'''
367| self.board = [[0 for col in range(self.Cols)]
368| for row in range(self.Rows)]
369|
370| if __name__ == '__main__':
371| print()
372|
373|
374| brd = chessboard()
375| print(brd)
376| print()
377|
378| nam = chessboard.__closure__[0].cell_contents
379| cls = chessboard.__closure__[1].cell_contents
380| print(f'{nam = }')
381| print(f'{cls = }')
382| print(f'{cls.Rows = }')
383| print(f'{cls.Cols = }')
384| print()
385|
386|
387| def Decorator1 (name):
388| '''Demo Decorator #1.'''
389| print(f'Decorator1({name})')
390|
391| def decorator (function):
392| '''Actual decorator function.'''
393|
394|
395| ftn_name = function.__qualname__
396| ftn_type = function.__class__.__name__
397| print(f'@[{name}]: {ftn_name} ({ftn_type})')
398|
399| def wrapper (*args, **kwargs):
400| '''Wrapper function.'''
401| print(f'[{name}].args: {args}')
402| print(f'[{name}].kwargs: {list(kwargs)}')
403|
404|
405| return function(*args, **kwargs)
406|
407|
408| return wrapper
409|
410|
411| return decorator
412|
413| def Decorator2 (function):
414| '''Demo Decorator #2.'''
415|
416| ftn_name = function.__qualname__
417| ftn_type = function.__class__.__name__
418| print(f'@Decorator2: {ftn_name} ({ftn_type})')
419|
420| def wrapper (*args, **kwargs):
421| '''Wrapper function.'''
422| print(f'decorator2.args: {args}')
423| print(f'decorator2.kwargs: {list(kwargs)}')
424|
425|
426| return function(*args, **kwargs)
427|
428|
429| return wrapper
430|
431|
432| from examples import Decorator1, Decorator2
433|
434| @Decorator1('Agatha')
435| @Decorator2
436| def function1(*args, **kwargs):
437| ''' Demo function #1.'''
438| ...
439| return
440|
441| @Decorator2
442| @Decorator1('Bertha')
443| def function2(*args, **kwargs):
444| ''' Demo function #2.'''
445| ...
446| return
447|
448| if __name__ == '__main__':
449| print()
450|
451| function1(21,42,fname='fred',fpath=r'C:\demo\hcc\python')
452| print()
453|
454| function1(1,2,3,4,5,x=0,y=0,z=0)
455| print()
456|
457| function2(1,2,3,4,5)
458| print()
459|
460| function2(cmd='reset',nup='SEA',pir='MIL')
461| print()
462|
463|
464| from time import perf_counter_ns
465|
466| def FunctionLogger (function):
467| '''Decorator for logging and timing function calls.'''
468|
469|
470| ftn_name = function.__qualname__
471| ftn_type = function.__class__.__name__
472| print(f'@Logger: {ftn_name} ({ftn_type})')
473|
474| class wrapper (list):
475| '''A wrapper class (rather than a function).'''
476|
477| def __init__ (self):
478| '''Initialize wrapper instance.'''
479| self.count = 0
480| self.timer = 0
481|
482| def __call__ (self, *args, **kwargs):
483| '''Decorator class instances must be callable!.'''
484| self.append(f'@[{self.timer:12d}]: {args} {kwargs}')
485| self.count += 1
486|
487|
488| t0 = perf_counter_ns()
489|
490|
491| retv = function(*args, **kwargs)
492|
493|
494| self.timer += perf_counter_ns() - t0
495|
496|
497| return retv
498|
499| @property
500| def milliseconds (self): return self.timer/pow(10,6)
501|
502| @property
503| def seconds (self): return self.timer/pow(10,9)
504|
505| def __str__ (self): return f'Logger:{ftn_name}'
506|
507|
508| return wrapper()
509|
510|
511| from time import sleep
512| from random import random
513| from examples import FunctionLogger
514|
515| @FunctionLogger
516| def function1 (a, b, c, d):
517| '''Demo function #1.'''
518| sleep(random() * 2.0)
519| return a+b+c+d
520|
521| @FunctionLogger
522| def function2 (a, b, c, d):
523| '''Demo function #2.'''
524| sleep(random() * 6.0)
525| return a*b*c*d
526|
527| if __name__ == '__main__':
528| print()
529|
530|
531| function1(0, 0, 0, 0)
532| function1(a=1, b=2, c=3, d=4)
533| function1(1, -1, 100, -99)
534| function1(21, 42, d=63, c=84)
535| function1(-9, 99, -999, 9999)
536| function1(9, 99, 999, 9999)
537|
538|
539| function2(0, 0, 0, 0)
540| function2(a=1, b=2, c=3, d=4)
541| function2(1, -1, 100, -99)
542| function2(21, 42, 63, 84)
543|
544| def dump_stats (ftn):
545| '''Dump function stats.'''
546| print(f'{ftn}: {ftn.count} calls, {ftn.seconds} secs')
547| for ix,line in enumerate(ftn, start=1):
548| print(f'{ix:02d}: {line}')
549| print()
550|
551| dump_stats(function1)
552| dump_stats(function2)
553|
554|
555| def ErrorRecorder (default_return_value):
556| '''Decorator function to catch and log errors.'''
557|
558| def decorator (function):
559| '''Actual decorator function.'''
560|
561|
562| ftn_name = function.__qualname__
563| ftn_type = function.__class__.__name__
564| print(f'@ErrorRecorder: {ftn_name} ({ftn_type})')
565|
566| def wrapper (*args, **kwargs):
567| '''Wrapper function.'''
568| try:
569| wrapper.count += 1
570|
571|
572| return function(*args, **kwargs)
573|
574| except Exception as e:
575| wrapper.errs.append((wrapper.count, e))
576|
577|
578| return default_return_value
579|
580|
581| wrapper.fctn = function
582| wrapper.count = 0
583| wrapper.errs = []
584|
585|
586| return wrapper
587|
588|
589| return decorator
590|
591|
592| from math import log
593| from examples import ErrorRecorder
594|
595| @ErrorRecorder(None)
596| def foobar (a, b, c):
597| '''Example function.'''
598| return (a*log(b))/c
599|
600| if __name__ == '__main__':
601| print()
602|
603| print(f' 1: result={foobar()}')
604| print(f' 2: result={foobar(1,2,3)}')
605| print(f' 3: result={foobar(7,8,9)}')
606| print(f' 4: result={foobar(-1,3,3.14159)}')
607| print(f' 5: result={foobar(2.718, 2.718, 2.718)}')
608| print(f' 6: result={foobar(0,4,5)}')
609| print(f' 7: result={foobar(3,0,5)}')
610| print(f' 8: result={foobar(3,4,0,-1)}')
611| print(f' 9: result={foobar(3,4)}')
612| print(f'10: result={foobar(3,4,5)}')
613| print(f'11: result={foobar(0,4,0)}')
614| print(f'12: result={foobar(0,0,0)}')
615| print(f'13: result={foobar(4,1,1)}')
616| print(f'14: result={foobar("4","2","0")}')
617| print(f'15: result={foobar(0,7,None)}')
618| print()
619|
620| print(f'function-name: {foobar.fctn.__qualname__}')
621| print(f'calls: {foobar.count}')
622| print(f'errs: {len(foobar.errs)}')
623| print()
624|
625| print(f'errors:')
626| for ix,err in enumerate(foobar.errs, start=1):
627| print(f'{ix:2d}: @{err[0]} {err[1]}')
628| print()
629|
630|
631| def foobar (a:int, b:float, c:str='', d:list=None) -> tuple:
632| '''Demo function with parameter and return annotations.'''
633| return (a, b, c, d)
634|
635| if __name__ == '__main__':
636| print()
637|
638| for item,value in foobar.__annotations__.items():
639|
640| vowel = 'n' if value.__name__[0] in 'aeiou' else ''
641|
642|
643| print(f'{item} is a{vowel} {value.__name__}')
644|
645| print()
646|
647|
648| def TypeCheck (ftn):
649| '''Type checking decorator.'''
650| getname = lambda obj: obj.__name__
651|
652|
653| anns = ftn.__annotations__
654| ins = [f'{k}:{getname(v)}' for k,v in anns.items() if k != 'return']
655| ret = anns['return'] if 'return' in anns else type(None)
656| print(f'TypeCheck: {getname(ftn)}({",".join(ins)}):{getname(ret)}')
657|
658| def wrapper (*args, **kwargs):
659| '''Wrapper function.'''
660|
661|
662| for arg,nam in zip(args, anns.keys()):
663| t0 = type(arg).__name__
664| t1 = getname(anns[nam])
665| check = 'OK' if type(arg) == anns[nam] else f'[{t0}≠{t1}]'
666| print(f'{getname(ftn)}: arg[{nam}]:{t1} = {arg}:{t0} {check}')
667|
668|
669| for nam,val in kwargs.items():
670| t0 = type(val).__name__
671| t1 = getname(anns[nam])
672| check = 'OK' if type(val) == anns[nam] else f'[{t0}≠{t1}]'
673| print(f'{getname(ftn)}: kwarg[{nam}]:{t1} = {val}:{t0} {check}')
674| print()
675|
676|
677| return ftn(*args, **kwargs)
678|
679|
680| return wrapper
681|
682|
683| from examples import TypeCheck
684|
685| @TypeCheck
686| def foobar (a:int=0, b:int=0, c:float=0.0) -> list:
687| '''Example function.'''
688| return [a, b, c]
689|
690| if __name__ == '__main__':
691| print()
692|
693| rv = foobar(42, '21', 3.1415)
694| rv = foobar(63, c=3)
695| rv = foobar(b=21, a=4.2, c=3.1415)
696| rv = foobar('42', [21], tuple('3.14'))
697|
698|
699|