3

In the following code how does app.run() find that hello() exists? I browsed the code and couldn't find the answer. I think the hello() doesn't get added to a list of routes until it is called, but how does it get called?

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

I'm not interested in Flask in particular. I'd just like to implement something similar myself.

What is this design pattern called?

tjk
  • 339
  • 3
  • 8

1 Answers1

4

Your assumption is wrong. Decorators are themselves executable code, and they are called when the function they decorate is defined, ie at import time. The code within the decorator can then add the route to its registry.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895