Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask Takin' Names LoginManager

Kyle Salisbury
seal-mask
.a{fill-rule:evenodd;}techdegree
Kyle Salisbury
Full Stack JavaScript Techdegree Student 16,363 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]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 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.

A moduleโ€™s __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 __main__ docs.

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