1

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nikhil Rupanawar
  • 4,061
  • 10
  • 35
  • 51
  • 1
    No other resources. Just read this [How can I make a chain of function decorators in Python?](http://stackoverflow.com/a/1594484/1903116) – thefourtheye Jan 19 '14 at 16:37
  • 1
    `myprint` is the inner function, so they're passed explicitly by you with: `('hii')`, and forwarded with `f(args[0])`. – BartoszKP Jan 19 '14 at 16:45
  • Nice ! both helped me. actually I am getting wrapped function object. myprint = makeitalic(myprint). What I am doing is calling wrapped. Is it correct? – Nikhil Rupanawar Jan 19 '14 at 16:48
  • decorators are basically syntactic sugar for what you're actually doing. For the decorator syntax you would delete the line `myprint = makeitalic(myprint)`, but then add `@makeitalic` above the `def`. – Free Monica Cellio Jan 19 '14 at 16:51
  • Are you confusing about how wrapped received the argument *args or how the makeitalic received func 'myprint', which part you are confusing, i hope i can try to explain it. – James Sapam Jan 21 '14 at 06:57

2 Answers2

2

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.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
-1

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.

Free Monica Cellio
  • 2,270
  • 1
  • 16
  • 15