Open In App

Why do we pass __name__ to the Flask class?

Last Updated : 07 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




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

Python3




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:

Why do we pass __name__ to the Flask class?

 

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.

Python3




print("My namme is : ", __name__)


Output:

What is __name__ in Python Flask?

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads