anonuser0428
anonuser0428

Reputation: 12363

'@' 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.

Upvotes: 4

Views: 305

Answers (1)

ovgolovin
ovgolovin

Reputation: 13430

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)

Upvotes: 5

Related Questions