This mini-kata explores Python decorators.
This project is super-simple. All code should happen in main.py
.
- Initial setup:
poetry install
- Running:
poetry run python main.py
All the steps below have corresponding branches—step1-implemented
, step2-implemented
, etc.—that contain one possible implementation of that particular step. Feel free to use those branches or to create your own implementations. (And if you do create your own, may I suggest branches like step1
, step2
?)
Run the basic program once without any changes. What is the output? What does it show for the function metadata?
- Wrap the
hello()
function—without using the decorator syntax—in atrace()
function so that you get the following output:What happened to the function metadata?🤖: function called 👋: Hello, world! 🤖: function returning
- Use the decorator syntax to wrap
hello()
with@trace
. Now what happened to the function metadata? Hint: yourtrace()
needs to use a nested function. - Modify
hello()
to accept aname
string. Use thatname
in the greeting, so thathello('John')
produces:Hint: you can pass🤖: function called 👋: Hello, John! 🤖: function returning
*args, **kwargs
from the inner function through to the wrapped function. - Support passing an
enabled
keyword argument to the@trace
decorator.- if
True
,@trace
should print out the additional logging - if
False
,@trace
should not print out the additional logging enabled
should be set toFalse
by default Hint: you'll need to add another layer of nested functions.
- if
- Use the decorator
@decorator
to simplify the implementation. Note that you'll need to add this dependency first viapoetry add decorator
. When we use@decorator
, what happens to our function metadata? Hint: all nested functions collapse, including their arguments, into a single, un-nested function.
One final note: we could also use the built-in @wraps decorator from the functools
module to simplify our decorator. Like @decorator
, @wraps
preserves function metadata; however, it does not collapse the nested functions. It is for that reason that I still prefer @decorator
for all your custom decorating needs.