Instructor: Sometimes in your code,
you might have the need for some logging to happen.
In this code exercise,
we're going to write a logging_decorator
and it's going to print the name
of the function that was called,
the arguments that was given
and also the returned output of that function.
Take a look in the description pane
and you'll see an example of what we want the output
to look like.
Without changing the body
of the function that we've called a_function
on lines eight and nine, create a decorator
to decorate that function and be able to log what you see
in the example output.
As before, you remember,
you can use function.__name__
to get the name of the function
and you can use the args to get hold of the arguments.
So create this decorator, decorate the necessary functions
and see if you manage to achieve the desired output.
First thing first is to define our decorator
and I've called it logging_decorator
that takes an input, which I'll call fn,
which is short for function.
You can call it whatever you like.
So next, let's define our wrapper function.
It's going to take the arguments that come in
and it's going to print
that you called the function.name,
and then we're going to insert the arguments
that were passed in.
That way we can log to the user which function they called
and which arguments were passed in,
which as you can imagine sometimes for debugging
that this might be quite handy to know.
Next, we get hold of the result
of running our function, which is decorated.
So we have our function being passed in
and we pass in the arguments at zero, one and two.
So in this case, we only have arguments
and remember that when we use args, we can get a list
of all of the inputs that were passed into the function.
So in this case, we take a look in the input pane.
We can see there are three inputs.
We take the arguments at position zero, one and two,
all three, pass it through the function,
whichever function we're going to decorate in the future.
And then we should end up with an output, which we assign
to the variable results.
And then we print it out and we say it returned
and then we insert the result using an f string.
And finally, we return the wrapper function.
The last part is actually decorating our function,
using the logging_decorator we created.
So line 10, we add that decorator to a_function
so that now every time a_function runs,
it's going to run the logging_decorator
and it's going to print out which function was called,
which arguments were passed in
and which results were returned.
And if you run the code as it is,
you should see the expected outcome.
If you have anything you need to change in your code or fix
or just to check, then head back to the previous slide
and you can update your code as needed.