Search code examples
pythondecorator

is there a way to see a functions changes after that it were decorated?


for example for the below code is there any tool to see the definition of the function that is decorated?

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
    return 'hello'

I tested inspect.getsource(index) but this only returns:

"@app.route('/')\ndef index():\n    return 'hello'\n"

Solution

  • If you intend to see what's the decorator @app.route() does, the answer lies in Python flask source code. I'm using flask 1.1.2 (the newest stable version currently is 2.0.0), and here is what it's defined in the file app.py, putting aside the many comments:

        def route(self, rule, **options):
            def decorator(f):
                endpoint = options.pop("endpoint", None)
                self.add_url_rule(rule, endpoint, f, **options)
                return f
    
            return decorator
    

    Basically it complements the behavior of a route function (aka rule here) by adding it to the route processing infrastructure, and adds to this processing a generic object f -- probably a function -- to be used in the contexts of route processing.

    The Python flask code is heavily commented, and it's very interesting to read it to get a finer idea of what flask does.