Python Forum

Full Version: Decorator toy code throws syntax errors
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am a newbie trying to learn programming. Here is my decorator toy code. It throws syntax error when I call the argument function.

def boldtext(fn):"""This is the 1st decorator function"""
result = "<b>" + fn + "</b>"
return result

def italicizetext(fn): """This is the 2nd decorator function"""
result = "<i>" + fn() + "</i>"
return result


@boldtext
@italicizetext

def printsampletext(): """This is the argument function"""
return "Some sample text!"

printsampletext()
Check out Harrison's tutorial on decorator's here:

https://pythonprogramming.net/decorators...-tutorial/
def decorator(function):
    """The decorator function"""
    def wrapper(text):
        print("Decorated function ahead")
        function(text)
        print("Decorated function behind")
    return wrapper

@decorator
def func(text):
    print(text)

func("Decorated function")
Output:
Decorated function ahead Decorated function Decorated function behind
Here is how to do a decorator. You can change completely the function behaviour that way. Instead, printing its own string it prints two more.
Thanks to both Tim and Bishop.