Kyle Salisbury9,385 Points
Can someone help me understand Flask(__name__) a little better?
I don't entirely understand why we put
app=Flask(__name__). For that matter I don't understand the part before where we put:
if __name__=='__main__': app.run(debug=DEBUG, host=HOST, port=PORT)
I appreciate the future help! :-)
[MOD: added ```python formatting -cf]
Chris FreemanTreehouse Moderator 57,144 Points
In Python, a few special read-only attributes are added to several object types, where they are relevant. Some of these are not reported by the dir() built-in function.
__name__ is set to the name of the current class, function, method, descriptor, or generator instance.
__name__ is set equal to
'__main__' when read from standard input, a script, or from an interactive prompt. Thus the comparison
if __name__ == "__main__":
checks to see if this module was called interactively and then calls the specified function to execute the code. So
app.run would only execute if this module was call interactively and would not execute if this module was imported into another module. See
According to the Flask documentation:
If you are using a single module (as in this example), you should use __name__ because depending on if it’s started as application or imported as module the name will be different ('__main__' versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at the Flask documentation.
More documents on Flask():
About the First Parameter
The idea of the first parameter is to give Flask an idea of what belongs to your application. This name is used to find resources on the filesystem, can be used by extensions to improve debugging information and a lot more.
So it’s important what you provide there. If you are using a single module, __name__ is always the correct value. If you however are using a package, it’s usually recommended to hardcode the name of your package there.
Post back if you need more help. Good luck!!!