Reputation: 95
I'm learning about decorators and found this useful thread that really helped me a lot. How to make a chain of function decorators?
Based on what I understand, decorators are just syntactic sugar. However I'm having trouble converting from the syntactic sugar code to non-syntactic sugar code.
# Decorators
def addBold(func):
def wrapper(*arg1):
print("Bold Added")
return '<b>' + func(*arg1) + '</b>'
return wrapper
def addItalic(func):
def wrapper(*arg1):
print("Italic Added")
return '<i>' + func(*arg1) + '</i>'
return wrapper
This code works:
@addBold
def getHTMLCode(passedText):
return passedText
newVar = getHTMLCode('Hello')
print(newVar)
# outputs: Bold Added <b>Hello</b>
I tried converting to non-syntactic sugar code, but this not work (TypeError: 'str' object is not callable
):
def getHTMLCode(passedText):
return passedText
newVar = addBold(getHTMLCode('Hello')) # returns wrapper
newVar()
What does the working code (second block) look like w/o the decorator syntactic sugar?
Upvotes: 0
Views: 37
Reputation: 39581
You need to pass the function you want wrapped to the decorator function and then call the returned wrapper with the arguments:
wrapped_getHTMLCode = addBold(getHTMLCode)
wrapped_getHTMLCode('Hello')
Notice how wrapped_getHTMLCode
works like the decorated version of getHTMLCode
. You call it with the string you want bolded, and it returns the string with HTML bold markup around it.
Upvotes: 2