How to Write a decorator to add a '$' sign to a number in Python

Published on Aug. 22, 2023, 12:20 p.m.

Certainly, here’s an example of a Python decorator that adds a ‘$’ sign to a number:

def add_dollar_sign(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return f'${result}'
    return wrapper

You can then apply this decorator to any function that returns a number, and it will add the ‘$’ sign to the result. For example:

@add_dollar_sign
def calculate_total_cost(price, quantity):
    return price * quantity

total_cost = calculate_total_cost(10, 5)
print(total_cost) # outputs "$50"

In this example, the add_dollar_sign decorator takes a function as an argument, defines a new function wrapper that calls the original function and adds a ‘$’ sign to the result, and finally returns the new function. The @add_dollar_sign syntax applies the decorator to the calculate_total_cost function, so that when it is called the result is automatically wrapped with the ‘$’ sign.

I hope this helps! Let me know if you have any more questions.

Tags:

related content