Search code examples
pythonfunctiondecorator

How to make function decorators with user input


I made function that wraps text with 3 decorators.But i have issue with user input. How to make it?

def bold(fn):
    def wrapper():
        return "<b>" + fn() + "</b>"
    return wrapper

def italic(fn):
    def wrapper():
        return "<i>" + fn() + "</i>"
    return wrapper

def underline(fn):
    def wrapper():
        return "<u>" + fn() + "</u>"
    return wrapper


@bold
@italic
@underline
def get_text():
    return "hello world"

print(get_text())

Solution

  • You should pass the parameter to the wrapper function too.

    def bold(fn):
        def wrapper(text):
            return "<b>" + fn(text) + "</b>"
        return wrapper
    
    def italic(fn):
        def wrapper(text):
            return "<i>" + fn(text) + "</i>"
        return wrapper
    
    def underline(fn):
        def wrapper(text):
            return "<u>" + fn(text) + "</u>"
        return wrapper
    
    
    @bold
    @italic
    @underline
    def get_text(text):
        return text
    
    usrInput = input()
    print(get_text(usrInput))