Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python decorators vs passing functions

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?

like image 287
Sam Dillard Avatar asked Apr 12 '17 22:04

Sam Dillard


People also ask

How are decorators different from functions?

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.

When should I use Python decorators?

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.

Are Python decorators necessary?

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.

What is the benefit of using a decorator Python?

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).


1 Answers

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)
like image 157
Adam Smith Avatar answered Oct 03 '22 22:10

Adam Smith