B13 - decorators

source: L Ramalho, Fluent Python, O'Riley(2022)

decorator

  • a callable that takes another function/class as an argument, which may perform some processing, and returns or replaces it with another function/class or callable object

@decorate
def target():
	print("running")
	
## same as

def target():
	print("running")
	
target = decorate(target)
	def deco(func):
		def inner():
			print("running inner()")
		return inner
		
	@deco 
	def target():
		print("running target()")
		
	target()
running inner()
def deco(func):
		def inner(*args, **kwargs): ## accepts any arguements
			print("running inner()")
			func()
		return inner
		
	@deco
	def target(destination):
		print("running target at {destination}")
		
	target()
registry = []


def register(func):
    print(f"Registering {func}")
    registry.append(func)
    return func


@register
def f1():
    print("Running f1")
    

@register
def f2():
    print("Running f2")
    

def f3():
    print("Running f3")
    

def main():
    print("Running main")
    print('registry:', registry)
    f1()
    f2()
    f3()


if __name__ == "__main__":
    main()
Registering <function f1 at 0x000001C974E58A40>
Registering <function f2 at 0x000001C974E58900>
Running main
registry: [<function f1 at 0x000001C974E58A40>, <function f2 at 0x000001C974E58900>]
Running f3

standard library

memorization

import functools
@functools.cache