All In One Script



PHP,HTLM,CSS,Jquery,AJAX,Javascript and etc doubts and sample codes

  • Home
  • Javascript
  • PHP
  • CSS
  • SQL/MYSQL

How to make a chain of function decorators in Python?

by Blogger 3:41:00 AM Python python-decorators python. decorator

How to make a chain of function decorators in Python?

How can I make two decorators in Python that would do the following?
@makebold
@makeitalic
def say():
   return "Hello"
...which should return:
"<b><i>Hello</i></b>"
I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works.

Solution :

Check out the documentation to see how decorators work. Here is what you asked for:
def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

print hello() ## returns "<b><i>hello world</i></b>"



READ MORE
SHARE :

Search This Blog

Followers

  • Popular
  • Recent
  • Comments

Instagram

About

Popular Posts

statcounter



statcounter



Template Created By ThemeXpose & Blogger Templates