[Tutor] basic decorator question

Mats Wichmann mats at wichmann.us
Mon Jul 24 11:49:03 EDT 2017


On 07/24/2017 08:33 AM, bruce wrote:
> Hi.
> 
> I've seen sites discuss decorators, as functions that "wrap" and
> return functions.
> 
> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? All the examples I've seen so far have a
> single internal function.
> 
> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?
> 
> But as a start, if you have pointers to any really "basic" step by
> step sites/examples I can look at, I'd appreciate it. I suspect I'm
> getting flumoxed by something simple.

wrap and return are not two distinct things, they're part of the same
process...  the general concept is that a decorator changes the result
of a function without modifying the function itself by returning a new
function object which does some other stuff in addition to running the
code of the original function object.

This is a really simple wrapper:

def my_decorator(some_function):
    def wrapper():
        print("Stuff happening before some_function() is called.")
        some_function()
        print("Stuff after some_function() is called.")
    return wrapper

If you have an unwrapped function:

def foo():
    print "This is the unwrapped function"

You can show this in action like this:

foo()
bar = my_decorator(foo)
bar()

function names are just handles to the function object, so the middle
line of those three is passing the original function object referred to
by foo to my_decorator, whose inner function returns a function object
which is runs some code before and after the original function.  If the
undecorated fuction does not need to be referred to, the previous often
gets written as:

foo = my_decorator(foo)
foo()

Now to add Python's magical decorator syntax:

@my_decorator
def bar():
    print "This is another unwrapped function"

bar()

So all the @my_decorator bit does is provide shorthand for the syntax

bar = my_decorator(bar)

Wasn't ultra-clear on your original question; if you wanted the
"happening before" and "happening after" to call out to other functions
instead of doing a print, you can. Is that what you mean by multiple
internal functions?

Does this clarify at all?

Do hunt some, there are some really good tutorials on decorators.



More information about the Tutor mailing list