decorator problem

Chris Rebert clp2 at rebertia.com
Tue Jan 10 00:15:53 EST 2012


On Mon, Jan 9, 2012 at 8:14 PM, contro opinion <contropinion at gmail.com> wrote:
> test1.py
>
> def deco(func):
>      print 'i am in deco'
>
> @deco
> def test():
>      print 'i am in test'
>
>
> when you run it ,you get :
> i am in deco
>
>
>
> test2.py
>
> def tsfunc(func):
>      def wrappedFunc():
>           print 'i am in deco'
>           return func()
>       return wrappedFunc
>
> @tsfunc
> def test():
>     print "i am in test"
>
> when you run test2.py,you can get nothing ,why can't i get :??
> i am in deco

Because that `print` is in wrappedFunc() [which in this case is A.K.A.
test()], which is only defined, never called. Try adding a call to
test() at the end of your script.
Contrast this with deco(), which has the `print` directly in its body
rather than inside a nested function definition.

Also, might I suggest reading a tutorial on decorators or asking on an
IRC channel, rather than pelting the mailing list with all these
simple and related questions in such a fairly short timeframe?
At least please keep all these in a single thread instead of starting
a new one every single time...

Cheers,
Chris



More information about the Python-list mailing list