[Tutor] Fwd: Re: basic decorator question

Alan Gauld alan.gauld at alan-g.me.uk
Mon Jul 24 13:52:09 EDT 2017

Bah, Forgot to ReplyAll...

-------- Forwarded Message --------

On 24/07/17 15:33, bruce wrote:

> But, I'm sooo confuzed! My real question though, can a decorator have
> multiple internal functions? 

Yes and classes too if you want. A decorator is just a
standard function in all respects. The only thing that makes
it a decorator is that it takes a function as input and returns
a function as a result (ie it observes the decorator protocol).
Internally it can do anything that is legal in any function,
including creating as many inner functions and data structures
and classes as it wants.

> And, if a decorator can have multiple internal functions, how would
> the calling sequence work?

The calling sequence is just like any other code, it starts
at the top and follows the program control logic until it
either hits a return statement of falls off the bottom
(implicitly returning None). Note that the inner functions
do not need to be part of the returned function, they could
just be there to create some fixed value that is then stored
and used in the returned function.


def f(g):
 def h(): return 42
 myValue = h()
 def z():
   return myValue
 return z

f() is a decorator that takes a function g. It uses an
internal function h() to calculate a value. It then creates
a second inner function z() which returns that value.
Finally the decorator returns z. Notice that neither g()
nor h() are used in the returned function z().

You would use it like so:

def aFunc():
   return 666

always42 = f(aFunc)
print( always42() )


def aFunc() :return 666

print(aFunc())   # --> prints 42 !

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list