I'm currently learning Python and have been at it for about six months. I've made a lot of progress and am now trying to wrap my head around decorators. I understand the general idea behind decorators and have written a handful of simple decorators in a basic format, but this time I am trying to write a function that can use a decorator more than once:
For example, the following:
def make_html(element):
def wrapped(func, *args, **kwargs):
return f'<{element}>' + func(*args, **kwargs) + f'</{element}>'
return wrapped
@make_html('strong')
def get_text(text='I code in Python.'):
return text
print(get_text)
Outputs this:
<strong>I code in Python.</strong>
However, if I actually call the function when I print:
print(get_text())
I get this:
Traceback (most recent call last):
File "AppData/Local/Programs/Python/Python38/search and sort2.py", line 98, in <module>
print(get_text())
TypeError: 'str' object is not callable
Similarly, if I try to use the same decorator more than once on a function:
@make_html('p')
@make_html('strong')
def get_text(text='I code in Python.'):
return text
I get this:
Traceback (most recent call last):
File "AppData/Local/Programs/Python/Python38/search and sort2.py", line 94, in <module>
def get_text(text='I code in Python.'):
File "Local/Programs/Python/Python38/search and sort2.py", line 83, in wrapped
return f'<{element}>' + func(*args, **kwargs) + f'</{element}>'
TypeError: 'str' object is not callable
Any ideas as to what is going wrong here? How can I use the same decorator more than once on a function, and why is my function being interpreted as a string?