OK... so I can give a decorator and argument, and that will then
return the function <decorate>. This expects one argument (and is a
decorator (?)). When decorate is called with f1 as the argument, it
returns new_f, which, when called will print <text> (passed to the
original decorator), together with the result of calling f1 with its
args.

I don't understand the scope of *args, as seen in the argument list of
new_f. It doesn't appear to be in the static scope of msg, or decorate
or new_f...

So what's happening here is that f1 is being replaced by your function new_f.
Note that though the definition of f1 has an 's' argument, the definition of
f1 after the application of a decorator has the 'args' and 'kwds' arguments of
new_f.

When you call a function passed into a decorator (e.g. the 'f' passed
into 'decorate' in your example above) you won't necessarily know what
arguments it takes. Using *args and **kwds says that you don't know what
these arguments are, which is probably true in most cases when you write a
decorator function.

Note that if you knew you were only ever going to use this decorator for
function f1, you could write it as:

<> wrote in message
news:...
> this is the smallest bit of code I could get to demonstrate what I
> want to understand...
>
> def msg(text):
> def decorate(f):
> def new_f(*args):
> print text, f(*args)
> return new_f
> return decorate
>
>
> @msg("Hello, ")
> def f1(s):
> return s
>
>
> if __name__ == '__main__':
> f1("world!")
>
>
> ~/src/python caw$ python dec_play.py
> Hello, world!
>
> OK... so I can give a decorator and argument, and that will then
> return the function <decorate>. This expects one argument (and is a
> decorator (?)). When decorate is called with f1 as the argument, it
> returns new_f, which, when called will print <text> (passed to the
> original decorator), together with the result of calling f1 with its
> args.
>
> I don't understand the scope of *args, as seen in the argument list of
> new_f. It doesn't appear to be in the static scope of msg, or decorate
> or new_f...

As with all parameters, 'args' is a local variable in the local namespace
of the function it is a parameter for, in this case new_f. I presume you
would call that 'local scope'. I do not know what you mean by 'static
scope' since that is not a term usually used in describing Python.

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!