def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makeitalic
@makebold
def hello():
return "hello world"
print(hello()) ## returns "<b><i>hello world</i></b>"
In this code, why not just define the functions makeitalic() and makebold() and pass in the function hello?
Am I missing something here or are decorators really better for more complicated things?
Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
Needless to say, Python's decorators are incredibly useful. Not only can they be used to slow down the time it takes to write some code, but they can also be incredibly helpful at speeding up code. Not only are decorators incredibly useful when you find them about, but it is also a great idea to write your own.
Python Decorator is a powerful tool which can help us manipulate functionality of a function, a test method just by adding @decorator_name. In Python, everything is object, which means every entity has some metadata (called attributes) and associated functionality (called methods).
In this code, why not just define the functions makeitalic() and makebold() and pass in the function hello?
You certainly could! Decorators are just syntactic sugar. Under the hood, what happens is:
@makeitalic
@makebold
def hello():
return "hello world"
becomes:
def hello():
return "hello world"
hello = makebold(hello)
hello = makeitalic(hello)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With