Trying to understand decorator. So, is it possible to call decorator inside a function, either by defining the function inline or independently ?
def deco(f):
print "In deco"
def wrp(*args, **kwargs):
print "In wrp"
return f(*args, **kwargs)
return wrp
@deco
def f1():
print "In f1"
def f2():
print "In f2"
def f3():
print "In f3"
# Calling independent function
# Error : Invalid syntax error
@deco
f2()
'''
@deco
f2()
Error : IndentationError: unexpected indent
'''
print "End f3"
def f4():
print "In f4"
# Making function inline
@deco
def f5():
print "In f5"
'''
Error : NameError: global name 'deco' is not defined
'''
print "End f4"
Also, explanation for error in f4() will be helpful.
I'm not quite sure what you are trying to do here. The @
is simply syntactic sugar for wrapping a function in another one: so @deco
before the definition of f1
is exactly the same as f1 = deco(f1)
afterwards.
So it simply doesn't make sense to "use" a decorator inside another function. If you really wanted to, you could do this:
deco(f2)()
ie, create the wrapper and then call it, but I have no idea why you would want to do that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.