Python decorators: background

Through searching, I found many tutorials that explain how it works, but not why it works that way. Now I know how to implement all 3 main use cases:

  • 1st: no arguments
  • 2nd: the function I want to decorate has arguments
  • 3rd: the decorator itself has arguments

I find the first and second use cases are very intuitive: Python sees the decorator and it says, "OK, decorator, here's your function - passing an argument - now give me something I can use instead."

1st use case: "Did you give me a function that takes no arguments? Works, thanks."

Second use case: "Did you give me a function that just takes * args and ** kwargs? Works, thanks

Now for the third use case with sample code:

def mydecorator(msg=""):
    def wrapper2(func):
        def wrapper(*args, **kwargs):
            func(*args, **kwargs)
            print "You know nothing about Python"
            print msg
        return wrapper
    return wrapper2

@mydecorator(msg="No, really, nothing.")
def printHello(name="Jon Snow"):
    print "Hello " + name

      

I don't understand the inner logic behind this. In this case, python can't say "Hello decorator, here's a function, gimme something I can use instead." This time python says, "Here is your msg argument, now give a function I can use instead of a function I didn't tell you (because I gave you msg instead)." So how now the decorator can get / work with func if it gets msg instead of func?

+3


source to share





All Articles