hello world
Let’s get meta:
How did that happen?
Let’s unpack the wrapper
:
Everything’s ‘better’ now:
But this:
Will trigger this:
And there are decorators for decorators…
Compare:
def simple_logger(func):
def wrapper(*args, **kwargs):
print(f"+ Executing '{func.__name__}' with args: {args}")
result = func(*args, **kwargs)
print(f" + Result is: {result}")
return result
return wrapper
@simple_logger
def add(a,b):
return a+b
add(2,5)
+ Executing 'add' with args: (2, 5)
+ Result is: 7
7
This would output:
try
and except
around every function you want to manage.We’ve barely scratched the surface, decorators can:
There’s lots, lost more, but using decorators effectively will seriously impress anyone interviewing you for a job while also helping you to understand a lot more about good programming!
Decorators • Jon Reades