Open In App

Why do we pass __name__ to the Flask class?

The __name__ is a built-in special variable that evaluates the name of the current module. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.

index.html



 Let’s look at a very basic boilerplate code for a flask application. These variables (name and age) will pass with values from the Python functions and are shown up here.




<html>
    <head>
        <title>My Name</title>
    </head>
    <body>
      <p>hey, my name is {{name}}, and i'm {{age}} years old</p>
    </body>
</html>

app.py



This specific code shall render the index.html file and we are passing the name of the current module and age as 13.




from flask import Flask, render_template
  
app = Flask(__name__)
app.config["DEBUG"] = True
  
  
@app.route('/')
def index():
    dic = {
        "name": __name__,
        "age": 13
    }
    return render_template('index.html', dic=dic)
  
  
if __name__ == "__main__":
    print("My namme is : ", __name__)
  
    app.run(debug=True)

Output:

 

We see an argument __name__ being passed in the Flask class, but what does it exactly do?  

According to the official flask documentation, a __name__ argument is passed in the Flask class to create its instance, which is then used to run the application. Flask uses it to know from where to get resources, templates, static files, etc required to run the application.




print("My namme is : ", __name__)

Output:

 


Article Tags :