7) Decorators Lesson

Python Decorators Step 3: Use Python Arguments

3 min to complete · By Martin Breuss

In the previous example, you defined msg inside of outer_func(). This makes it a hard-coded message that you can't change. In this lesson, you'll learn how to define this message elsewhere and see it flow down your function scopes like a beautiful autumn leaf in a cascading waterfall.

Functions with Python Args

You'll start by changing your function definition of outer_func() to accept an argument (or args):

def outer_func(msg):
    def inner_func():
        print(msg)
    return inner_func

Same as in the previous example, the value of msg will be available inside your inner_func() even though it came from the outer_func(). Unlike before, msg is not defined in the body of outer_func() but arrives there as an argument.

Flexibility

This change allows you to send whatever message you want to outer_func() and, because of how scopes work, also into inner_func(). This again means that you can call the reference to inner_func() to print the message back to you:

say_wee = outer_func("weee")
say_wee()  # OUTPUT: weee

Try running this code in your text editor and pass other messages to your function-burrito. As you can see, the passed argument propagates through the message scope and comes back out at the end of this function pipeline.

In the next lesson, you'll take these two nested functions and create your first empty decorator from them.

Summary: Use Python Arguments

  • Arguments can be passed to a function
  • Arguments are available in the scope of your inner functions without the need to explicitly pass them forward
  • Using Python arguments increases the flexibility of your function