Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'@' python decorator used to do something similar to method overriding in java?

I am relatively new to python and have just recently been exposed to the '@' python decorator. I know it has many uses but I would like to clarify if my understanding of one of its uses more specifically its use in the following code, is correct.

@app.before_request
def before_request():
    g.db = connect_db()

I came across the decorator while working with Flask and am wondering whether the above code in python uses the '@' decorator to 'override' the method 'before_request' in the 'app' class. I don't know if python has any other form of method overriding like java but since I know java it would be easier for me to understand it this way if it is indeed the case.

like image 540
anonuser0428 Avatar asked Sep 06 '25 12:09

anonuser0428


1 Answers

In Python functions are first class objects, so that they may be passed as parameters.

I'll rewrite your function for the clarity of the following explanation:

@app.before_request
def f():
    g.db = connect_db()

First, app.before_request is function.

What happens here is the following:

def f():
    g.db = connect_db()

f = app.before_request(f)

So, function app.before_request is applied to function f.

As app.before_request is used as decorator, the result of app.before_request is assigned again to f. But in this case it doesn't matter. What is imporatant is that app.before_request makes something internally with f to make use of it.

Decorator is used just for concise and beautiful way of describing it.

You can achieve the same by this code (which I think is less readable than the one with decorator):

def f():
    g.db = connect_db()

app.before_request(f)
like image 182
ovgolovin Avatar answered Sep 09 '25 11:09

ovgolovin