Question

I have following decorator example

def makeitalic(f):
    def wrapped(*args, **kwargs):     
       return "<I>" + f(args[0]) + "</I>"
    return wrapped

def myprint(text):
    return text


myprint = makeitalic(myprint)
print myprint('hii')

Output:
<I>hii</I>

How does the wrapped function (inner function) get the arguments of the original function?

Was it helpful?

Solution

The wrapped function doesn't get the arguments of the original function. It gets arguments that it can (and usually does) choose to pass on to the original function.

When you do myprint = makeitalic(myprint), the name myprint now refers to the wrapped function. It no longer refers to the function defined earlier as myprint.

So, when you call myprint('hii'), you are calling the wrapped function. The original function has no arguments yet because it has never been called.

Inside wrapped, you make a call to f. This is the original function, and you pass it args[0], which is 'hii'. So, now the original function is called. It gets the first argument of the wrapped function, because that's what you chose to pass it.

OTHER TIPS

thefourtheye already linked to the full explanation, so here's the shortest explanation that could possibly answer your question: the (*args, **kwargs) represents all arguments passed to the wrapped function. args is a tuple and kwargs is a dictionary. So when the wrapped function references args[0], it means "the first argument that was passed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top