2025-10-20_python-decorators-more.html
001|
002|
003|
004|
005| def DataRecorder (which):
006| '''Decorator for logging a specific parameter of function calls.'''
007|
008| if not (isinstance(which,int) or isinstance(which,str)):
009| raise TypeError(f'Parameter spec must be int or string.')
010|
011| def decorator (function):
012| '''Actual decorator function returned in initialization.'''
013| ftn_name = function.__qualname__
014|
015|
016| def wrapper (*args, **kwargs):
017| '''Wrapper function.'''
018| wrapper.count += 1
019|
020|
021|
022| if isinstance(which,int) and (which < len(args)):
023| arg = args[which]
024| wrapper.data.append((wrapper.count, arg))
025|
026|
027| elif isinstance(which,str) and (which in kwargs):
028| arg = kwargs[which]
029| wrapper.data.append((wrapper.count, arg))
030|
031|
032| return function(*args, **kwargs)
033|
034|
035| wrapper.count = 0
036| wrapper.data = []
037|
038|
039| return wrapper
040|
041|
042| return decorator
043|
044|
045| from examples import DataRecorder
046|
047| @DataRecorder(2)
048| def function1 (x=0, y=0, z=0):
049| '''Demo function #1.'''
050| return x*y*z
051|
052| @DataRecorder('y')
053| def function2 (x=0, y=0, z=0):
054| '''Demo function #2.'''
055| return x*y*z
056|
057| if __name__ == '__main__':
058| print()
059|
060|
061| function1()
062| function1(1)
063| function1(1,2)
064| function1(1,2,3)
065| function1(4,5,6)
066| function1(7,8,9)
067| print()
068|
069|
070| function2()
071| function2(x=1,y=2)
072| function2(x=2,z=9)
073| function2(3, y=5)
074| function2(x=7,y=8,z=9)
075| print()
076|
077|
078| vals = ", ".join(f'[{ix}]{v}' for ix,v in function1.data)
079| print(f'function1: {function1.count} calls')
080| print(f'values: {vals}')
081| print()
082|
083|
084| vals = ", ".join(f'[{ix}]{v}' for ix,v in function2.data)
085| print(f'function2: {function2.count} calls')
086| print(f'values: {vals}')
087| print()
088|
089|
090| def StringHandler (arg_indexes, kw_names, ftn_list):
091| '''Decorator for string handling.'''
092|
093| def decorator (function):
094| '''Actual decorator function.'''
095| ftn_name = function.__qualname__
096|
097|
098| def wrapper (*args, **kwargs):
099| '''Wrapper function.'''
100|
101| ftns = list(ftn_list)
102| _args = list(args)
103|
104|
105| for ax in arg_indexes:
106| s = _args[ax]
107| f = ftns.pop(0)
108| _args[ax] = f(s)
109|
110|
111| for kw in kw_names:
112| s = kwargs[kw]
113| f = ftns.pop(0)
114| kwargs[kw] = f(s)
115|
116|
117| retv = function(*tuple(_args), **kwargs)
118|
119|
120| if 0 < len(ftns):
121| f = ftns.pop(0)
122| retv = f(retv)
123|
124|
125| return retv
126|
127|
128| return wrapper
129|
130|
131| return decorator
132|
133|
134| from examples import StringHandler
135|
136| caps = lambda s:s.upper()
137| nocaps = lambda s:s.lower()
138| clean = lambda s:s.strip()
139|
140|
141| @StringHandler([0,1,2], [], [clean,clean,clean])
142| @StringHandler([1,2], ['x','y'], [caps,caps,caps,caps,nocaps])
143| def string_function (a, b, c, x='', y='', z=''):
144| '''Example function taking a bunch of strings.'''
145| print(f'a: {a}')
146| print(f'b: {b}')
147| print(f'c: {c}')
148| print(f'x: {x}')
149| print(f'y: {y}')
150| print(f'z: {z}')
151| print()
152| return f'{a}-{b}-{c}:{x}-{y}-{z}'
153|
154| if __name__ == '__main__':
155| print()
156|
157| args1 = [' dog\n', '\tcat\t', 'horse ']
158| props1 = dict(x='steak', y='eggs', z='bacon')
159| t = string_function(*args1, **props1)
160| print(f'rv={t}')
161| print()
162|
163| args2 = [' apple ', ' orange\n\n', '\t\tgrape\n']
164| props2 = dict(x='burger', y='fries', z='coke')
165| t = string_function(*args2, **props2)
166| print(f'rv={t}')
167| print()
168| print()
169|
170|
171| def Byte2String (which=1, encoding='utf8'):
172| '''Decorator for converting bytes to string.'''
173|
174|
175|
176| ix = which - 1
177|
178| def decorator (function):
179| '''Decorator function.'''
180| ftn_name = function.__qualname__
181|
182|
183| def wrapper (*args):
184| '''Wrapper function.'''
185| _args = list(args)
186|
187|
188| if 0 <= ix:
189|
190| _args[ix] = str(_args[ix], encoding=encoding)
191|
192|
193| retv = function(*_args)
194|
195|
196| if ix < 0:
197|
198| return str(retv, encoding=encoding)
199|
200|
201| return retv
202|
203|
204| return wrapper
205|
206|
207| return decorator
208|
209| def String2Byte (which=1, encoding='utf8'):
210| '''Decorator for converting string to bytes.'''
211|
212|
213|
214| ix = which - 1
215|
216| def decorator (function):
217| '''Decorator function.'''
218| ftn_name = function.__qualname__
219|
220|
221| def wrapper (*args):
222| '''Wrapper function.'''
223| _args = list(args)
224|
225|
226| if 0 <= ix:
227|
228| _args[ix] = bytes(_args[ix], encoding=encoding)
229|
230|
231| retv = function(*_args)
232|
233|
234| if ix < 0:
235|
236| return bytes(retv, encoding=encoding)
237|
238|
239| return retv
240|
241|
242| return wrapper
243|
244|
245| return decorator
246|
247|
248| from examples import String2Byte, Byte2String
249|
250| '''Return an object's typename.'''
251| typename = lambda obj: type(obj).__name__
252|
253| @String2Byte(2)
254| def function1 (n:int, data:bytes, z:float) -> bytes:
255| '''Demo function #1.'''
256| return data
257|
258| @Byte2String(3)
259| def function2 (a:str, b:int, data:str) -> str:
260| '''Demo function #2.'''
261| return data
262|
263| @String2Byte(0)
264| def function3 (data:str, x:int) -> str:
265| '''Demo function #3.'''
266| return data
267|
268| @Byte2String(0, 'utf16')
269| def function4 (data:bytes, m:float, n:float) -> bytes:
270| '''Demo function #4.'''
271| return data
272|
273| if __name__ == '__main__':
274| print()
275|
276| retv = function1(11, 'Ćóñàφωċĥ', 3.14159)
277| print(f'{retv} ({typename(retv)})')
278| print()
279|
280| retv = function2('eb', 42, bytes("Hello",encoding='utf8'))
281| print(f'{retv} ({typename(retv)})')
282| print()
283|
284| retv = function3('질쯊췌쿎퇐폒', 21)
285| print(f'{retv} ({typename(retv)})')
286| print()
287|
288| retv = function4(bytes("World",encoding='utf16'), 2.7, 1.6)
289| print(f'{retv} ({typename(retv)})')
290| print()
291|
292|
293| from examples import String2Byte, Byte2String
294|
295| typename = lambda obj: type(obj).__name__
296|
297| @String2Byte()
298| @Byte2String(0)
299| def bytes_handling_function (data:bytes) -> bytes:
300| print(f'bytes_handling_function({len(data)} {typename(data)})')
301| print(f'data = {data.hex(".")}')
302| print()
303| return data
304|
305| if __name__ == '__main__':
306| print()
307|
308| retv = bytes_handling_function("Hello, World!")
309| print(f'{retv = }')
310| print()
311|
312|
313| from time import perf_counter_ns
314|
315| FunctionTimes = {'main':{}}
316|
317| def FunctionTimer (group='main'):
318| '''Decorator function for timing functions.'''
319|
320|
321|
322| if group not in FunctionTimes:
323| FunctionTimes[group] = {}
324|
325| def decorator (function):
326| '''The actual decorator function.'''
327| func_name = function.__qualname__
328|
329|
330| if func_name not in FunctionTimes[group]:
331| FunctionTimes[group][func_name] = [0.0]
332|
333| def wrapper (*args, **kwargs):
334| '''The wrapper function.'''
335|
336|
337|
338| t0 = perf_counter_ns()
339| retv = function(*args, **kwargs)
340| t1 = perf_counter_ns() - t0
341|
342|
343| FunctionTimes[group][func_name][0] += t1
344| FunctionTimes[group][func_name].append(t1)
345|
346|
347|
348| return retv
349|
350|
351| return wrapper
352|
353|
354| return decorator
355|
356| FunctionTimer.data = FunctionTimes
357|
358|
359| from time import sleep
360| from random import random
361| from examples import FunctionTimer
362|
363| FAST = False
364| DELAY = 1/3
365| plural = lambda n: '' if n==1 else 's'
366|
367| @FunctionTimer()
368| def fast_function (t=0.777, d=0.456):
369| u = DELAY if FAST else t
370| v = 0 if FAST else d
371| sleep(u + (random() * v))
372|
373| @FunctionTimer('group1')
374| def slow_function (t=2.71828, d=1.111):
375| u = DELAY if FAST else t
376| v = 0 if FAST else d
377| sleep(u + (random() * v))
378|
379| @FunctionTimer('group1')
380| def another_slow_function (t=2.71828, d=1.111):
381| u = DELAY if FAST else t
382| v = 0 if FAST else d
383| sleep(u + (random() * v))
384|
385| @FunctionTimer('group2')
386| def slower_function (t=3.14159, d=1.616):
387| u = DELAY if FAST else t
388| v = 0 if FAST else d
389| sleep(u + (random() * v))
390|
391| @FunctionTimer('group2')
392| def another_slower_function (t=3.14159, d=1.616):
393| u = DELAY if FAST else t
394| v = 0 if FAST else d
395| sleep(u + (random() * v))
396|
397| @FunctionTimer('group3')
398| def slowest_function (t=6.28318, d=2.718):
399| u = DELAY if FAST else t
400| v = 0 if FAST else d
401| sleep(u + (random() * v))
402|
403| if __name__ == '__main__':
404| print()
405| print('Running some slow functions... (be patient)\n')
406|
407| fast_function()
408| slow_function()
409| another_slow_function()
410| fast_function()
411| slower_function()
412| another_slower_function()
413| fast_function()
414|
415| print('\n...Hang in there...\n')
416|
417| fast_function()
418| slow_function()
419| another_slow_function()
420| fast_function()
421| slower_function()
422| another_slower_function()
423| fast_function()
424|
425| print('\n...Got a bit more to go...\n')
426|
427| fast_function()
428| slow_function()
429| another_slow_function()
430| fast_function()
431| slower_function()
432| another_slower_function()
433| fast_function()
434| slowest_function()
435| fast_function()
436| slowest_function()
437| fast_function()
438| print('\n...Done!\n')
439|
440| for ch in FunctionTimer.data:
441| grp = FunctionTimer.data[ch]
442| print(f'[{ch}] ({len(grp)} function{plural(len(grp))})')
443|
444| for nam in sorted(grp):
445| print(f':{nam}::')
446| ts = [f'{d/pow(10,9):.6f}' for d in grp[nam]]
447| print(f'{", ".join(ts)}')
448| print()
449| print()
450|
451|
452| class ExampleClass:
453|
454| ...
455|
456| def __repr__ (self):
457| tname = self.__class__.__name__
458| return f'<{tname} @{id(self):08x}>'
459|
460| ...
461|
462|
463| def AddSimpleReprMethod (cls):
464| '''Decorator function to add repr() function to a class.'''
465|
466|
467| def my_repr (self):
468| return f"<{type(self).__name__} @{id(self):08x}>"
469|
470| cls.__repr__ = my_repr
471| return cls
472|
473|
474| from examples import AddSimpleReprMethod
475|
476| @AddSimpleReprMethod
477| class EgClass1:
478| ...
479|
480| @AddSimpleReprMethod
481| class EgClass2:
482| ...
483|
484| @AddSimpleReprMethod
485| class EgClass3:
486| ...
487|
488| @AddSimpleReprMethod
489| class EgClass4:
490| ...
491|
492| @AddSimpleReprMethod
493| class EgClass5:
494| ...
495|
496| if __name__ == '__main__':
497| print()
498|
499| c1 = EgClass1()
500| c2 = EgClass2()
501| c3 = EgClass3()
502| c4 = EgClass4()
503| c5 = EgClass5()
504| print(f'c1: {c1}')
505| print(f'c2: {c2}')
506| print(f'c3: {c3}')
507| print(f'c4: {c4}')
508| print(f'c5: {c5}')
509| print()
510|
511|
512| def AddReprMethod (cls):
513| '''Decorator function to modify repr() function of a class.'''
514|
515|
516| def my_repr (self):
517| attrs = (f"{key}={val!r}" for key,val in vars(self).items())
518| return f"{type(self).__name__}({', '.join(attrs)})"
519|
520| cls.__repr__ = my_repr
521| return cls
522|
523| from examples import AddReprMethod
524|
525| @AddReprMethod
526| class foobar:
527| '''Example class #1.'''
528| def __init__ (self, name):
529| self.name = name
530| self.count = 0
531| self.timer = 0.0
532|
533| @AddReprMethod
534| class tasbot:
535| '''Example class #2.'''
536| def __init__ (self, x:float=0.0, y:float=0.0):
537| self.x = x
538| self.y = y
539|
540| if __name__ == '__main__':
541| print()
542|
543| foo1 = foobar('Fred')
544| foo2 = foobar('Barney')
545| print(f'{foo1!r}\n{foo2!r}\n')
546|
547| tas1 = tasbot()
548| tas2 = tasbot(4.2, 2.1)
549| print(f'{tas1!r}\n{tas2!r}\n')
550|
551|
552| from examples import AddReprMethod
553|
554| @AddReprMethod
555| class faxbun:
556| '''Example class #3.'''
557| def __init__ (self, name:str, x:float=0.0, y:float=0.0):
558| self.name = name
559| self.x = x
560| self.y = y
561|
562| if __name__ == '__main__':
563| print()
564|
565| obj1 = faxbun('Sam')
566| obj2 = faxbun('Judy', 4.2, 2.1)
567|
568| txt1 = repr(obj1)
569| txt2 = repr(obj2)
570| print(txt1, txt2, '', sep='\n')
571|
572| dup1 = eval(txt1)
573| dup2 = eval(txt2)
574| print(f'{dup1} [type={type(dup1).__name__}]')
575| print(f'{dup2} [type={type(dup2).__name__}]')
576| print()
577|
578|
579| def StaticMethod (method):
580| '''Decorator to turn a method into a static method.'''
581|
582|
583| ftn_name = method.__name__
584|
585|
586| class StaticMethodProperty:
587| '''Property class to implement the static method wrapper.'''
588|
589| def __init__ (self, ftn):
590|
591| self.method = ftn
592|
593| def __set_name__ (self, owner, name):
594|
595| self.name = name
596|
597| def __get__ (self, obj, cls):
598| '''Access the property.'''
599| caller = '<null>' if obj is None else ObjIdStr(obj)
600|
601| def proxy (*args, **kwargs):
602| '''Proxy function that wraps class method.'''
603| return self.method(*args, **kwargs)
604| return proxy
605|
606| def __set__ (self, obj, value):
607| '''(Only protects calls on instance objects.'''
608| raise NotImplementedError(f'You may not modify {self.name}!')
609|
610| def __delete__ (self, obj):
611| '''(Only protects calls on instance objects.'''
612| raise NotImplementedError(f'You may not delete {self.name}!')
613|
614|
615| return StaticMethodProperty(method)
616|
617| ObjIdStr = lambda obj: f'<{type(obj).__name__} @{id(obj):08x}>'
618|
619| def ClassMethod (method):
620| '''Decorator to turn a method into a class method.'''
621|
622| ftn_name = method.__name__
623|
624|
625| class ClassMethodProperty:
626| '''Property class to implement the class method wrapper.'''
627|
628| def __init__ (self, ftn):
629|
630| self.method = ftn
631|
632| def __set_name__ (self, owner, name):
633|
634| self.name = name
635|
636| def __get__ (self, obj, cls):
637| '''Access the property.'''
638| caller = '<null>' if obj is None else ObjIdStr(obj)
639|
640| def proxy (*args, **kwargs):
641| '''Proxy function that wraps class method.'''
642| return self.method(cls, *args, **kwargs)
643| return proxy
644|
645| def __set__ (self, obj, value):
646| '''(Only protects calls on instance objects.'''
647| raise NotImplementedError(f'You may not modify {self.name}!')
648|
649| def __delete__ (self, obj):
650| '''(Only protects calls on instance objects.'''
651| raise NotImplementedError(f'You may not delete {self.name}!')
652|
653|
654| return ClassMethodProperty(method)
655|
656|
657| from math import sqrt
658| from examples import StaticMethod, ClassMethod
659|
660| class point:
661| '''Example class.'''
662| dent = 42
663|
664| def __init__ (self, x=0.0, y=0.0):
665| '''New point instance.'''
666| self.x = float(x)
667| self.y = float(y)
668|
669| @StaticMethod
670| def distance (a, b) -> float:
671| '''Example static method.'''
672| print(f'distance({a}, {b})')
673| return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2))
674|
675| @ClassMethod
676| def setdent (cls, value):
677| '''Example class method.'''
678| print(f'setdent({cls.__name__}, {value})')
679| point.dent = value
680| return point.dent
681|
682| def __repr__ (self):
683| return f'<{type(self).__name__} [{self.dent}] @{id(self):08x}>'
684|
685| def __str__ (self):
686| return f'[{self.x:.3f} x {self.y:.3f}]'
687|
688| if __name__ == '__main__':
689| print()
690| p0 = point()
691| p1 = point(-5, +5)
692|
693| print(f'{point.distance(p0, p1)}')
694| print(f'{p0.distance(p0, p1)}')
695| print()
696|
697| print(f'{point.setdent(27)}')
698| print(f'{p0.setdent(31)}')
699| print()
700|
701|
702| from examples import StaticMethod, ClassMethod, ObjIdStr
703|
704| class TestClass:
705| '''Example class #1.'''
706|
707| @StaticMethod
708| def barfoo (a, b, c):
709| return a*b*c
710|
711| @ClassMethod
712| def foobar (cls, x, y):
713| return x+y
714|
715| def __repr__ (self):
716| return ObjIdStr(self)
717|
718| if __name__ == '__main__':
719| print()
720|
721|
722| print(f'{TestClass.barfoo(21,42,63)=}')
723| print(f'{TestClass.foobar(21,42)=}')
724| print()
725|
726|
727| g = TestClass()
728| print(f'{g=}')
729| print(f'{g.barfoo(63,84,108)=}')
730| print(f'{g.foobar(63,84)=}')
731| print()
732|
733|
734| try: g.barfoo = [1,2,3]
735| except Exception as e: print(e)
736|
737| try: del g.barfoo
738| except Exception as e: print(e)
739|
740|
741| try: g.foobar = [1,2,3]
742| except Exception as e: print(e)
743|
744| try: del g.foobar
745| except Exception as e: print(e)
746| print()
747|
748|
749| try:
750| tmp = TestClass.barfoo
751| TestClass.barfoo = [1,2,3]
752| print(f'{TestClass.barfoo=}')
753| except Exception as e: print(e)
754| finally: TestClass.barfoo = tmp
755|
756| try:
757| del TestClass.barfoo
758| print(f'{hasattr(TestClass,"barfoo")=}')
759| except Exception as e: print(e)
760|
761|
762| try:
763| tmp = TestClass.foobar
764| TestClass.foobar = [1,2,3]
765| print(f'{TestClass.foobar=}')
766| except Exception as e: print(e)
767| finally: TestClass.foobar = tmp
768|
769| try:
770| del TestClass.foobar
771| print(f'{hasattr(TestClass,"foobar")=}')
772| except Exception as e: print(e)
773| print()
774|
775|
776| class BasicDecoratorClass:
777| '''Basic Decorator *class*. Use instances for decorators.'''
778|
779| class DecoratorFunctionClass:
780| '''Decorator class for wrapping a function.'''
781|
782| def __init__ (self, function):
783| '''New wrapper instance; receives decorated function.'''
784| print(f'@DecoratorFunction({function})')
785| self.function = function
786|
787| def __call__ (self, *args, **kwargs):
788| '''Call to the decorated function.'''
789| print(f'Decorator({len(args)} args, {len(kwargs)} kwargs)')
790|
791|
792| return self.function(*args, **kwargs)
793|
794| def __init__ (self):
795| '''New decorator instance.'''
796| print(f'@Decorator()')
797|
798| def __call__ (self, function):
799| '''Return a new wrapper for a function.'''
800| return BasicDecoratorClass.DecoratorFunctionClass(function)
801|
802|
803| from examples import BasicDecoratorClass
804|
805| @BasicDecoratorClass()
806| def function0 ():
807| return (21, 42, 63)
808|
809| @BasicDecoratorClass()
810| def function1 (x:int, y:int, z:float, a:str, b:str):
811| return (((x*y)/z), a+b)
812|
813| if __name__ == '__main__':
814| print()
815|
816| retv = function0()
817| print(f'{retv=}')
818| print()
819|
820| retv = function1(21,42, 3.14159, 'Hello, ', 'World!')
821| print(f'{retv=}')
822| print()
823|
824| print()
825|
826|
827|