title: how do decorated functions work in flask/python? (app.route)
body: <p>Edit 2: I misunderstood how decorators work. The decorator is run even if the decorated function is not called (even though you might not see it's effects). function = dec(function) would be an equivalent way of showing what a decorator does and obviously in that scenario the dec() function runs without any calls to function().</p>
  
  <p>Edit: Why is my post being down voted with no explanation? How can I fix it? There are multiple answers, one which clearly answers the question. What is the issue?</p>
  
  <p>I've been learning about decorators in python and I think I have a good grasp on them. However I am still slightly confused about how the app.route decorator works in flask. By my understanding the decorator changes the behavior of a function but does not run unless the function is called. So if I have:</p>
  
  <pre><code>@app.route("/")
  def hello():
      return "Hello world"
  
  hello()
  </code></pre>
  
  <p>The hello function will get passed to app.route and whatever behavior the decorator dictates will execute. However in flask apps the function itself never appears to be run (in my above example it is). How is the route function/decorator executed if the function it decorates is never called? I know that app.route essentially stores the "/" along with its corresponding function in a dictionary but I don't understand how this code is ever executed without any calls of the decorated function. I assume it is somehow connected to the app.run at the end of flask apps but I am unclear on how app.run can call the functions you defined.</p>
  
  <p>Edit: to add to what I've shown here. There is an example from this explanation: <a href="https://ains.co/blog/things-which-arent-magic-flask-part-1.html" rel="noreferrer">https://ains.co/blog/things-which-arent-magic-flask-part-1.html</a> That raises the same questions. I would think that hello() needs to be called in order for the route function to do anything.</p>
  
  <pre><code>class NotFlask():
      def __init__(self):
          self.routes = {}
  
      def route(self, route_str):
          def decorator(f):
              self.routes[route_str] = f
              return f
  
          return decorator
  
      def serve(self, path):
          view_function = self.routes.get(path)
          if view_function:
              return view_function()
          else:
              raise ValueError('Route "{}"" has not been 
  registered'.format(path))
  
  
  app = NotFlask()
  
  @app.route("/")
  def hello():
      return "Hello World!"
  </code></pre>