Python Forum
Decorator toy code throws syntax errors
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decorator toy code throws syntax errors
#1
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()
Reply
#2
Check out Harrison's tutorial on decorator's here:

https://pythonprogramming.net/decorators...-tutorial/
Reply
#3
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.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#4
Thanks to both Tim and Bishop.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Are there errors in the code for my coin toss systems? Matlibplot is too perfect . Coolkat 0 376 Nov-13-2023, 11:54 AM
Last Post: Coolkat
  the order of running code in a decorator function akbarza 2 522 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Syntax error while executing the Python code in Linux DivAsh 8 1,584 Jul-19-2023, 06:27 PM
Last Post: Lahearle
  Code is returning the incorrect values. syntax error 007sonic 6 1,227 Jun-19-2023, 03:35 AM
Last Post: 007sonic
  Curious about decorator syntax rjdegraff42 14 2,091 May-03-2023, 01:21 PM
Last Post: rjdegraff42
Photo Visual studio code unable to color syntax on python interpreter tomtom 4 6,904 Mar-02-2022, 01:23 AM
Last Post: tomtom
  pymysql: insert query throws error wardancer84 12 4,584 Jan-28-2022, 06:48 AM
Last Post: wardancer84
  My code won't say Player wins or computer wins. No errors. its_a_meLuigi64 2 1,627 Dec-01-2021, 04:43 PM
Last Post: its_a_meLuigi64
  ABC Module and @property decorator, Pythonic Way? muzikman 21 5,664 Aug-18-2021, 06:08 PM
Last Post: muzikman
  Syntax errors: Struggling to setup enviroment and load packages AH56 5 2,785 Jun-30-2021, 01:01 PM
Last Post: AH56

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020