-1

How can I make two decorators in Python that would do the following?

@bold_tag
@italic_tag
def greet():
   return input()

Input: Hello

Output should be

"<b><i>Hello</i></b>"
  • 2
    I'm not sure chaining is really your problem. If you can write `italic_tag` correctly, it should be obvious how `bold_tag` should be written. – chepner Jan 24 '22 at 18:17
  • 2
    Keep in mind that if decorator syntax didn't exist, you'd just define `greet`, then write `greet = bold_tag(italic_tag(greet))`. – chepner Jan 24 '22 at 18:18

1 Answers1

1

They're just regular decorators, nothing to it...

Using functools.wraps makes sure the wrapped function smells like the original.

from functools import wraps


def bold_tag(fn):
    @wraps(fn)
    def wrap(*args, **kwargs):
        return f'<b>{fn(*args, **kwargs)}</b>'

    return wrap


def italic_tag(fn):
    @wraps(fn)
    def wrap(*args, **kwargs):
        return f'<i>{fn(*args, **kwargs)}</i>'

    return wrap


@bold_tag
@italic_tag
def greet(s):
    return f"Hello, {s}!"


print(greet("you"))

The output is

<b><i>Hello, you!</i></b>
AKX
  • 152,115
  • 15
  • 115
  • 172