Python Build a Social Network with Flask Takin' Names LoginManager

Kyle Salisbury
Kyle Salisbury
10,975 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__':, host=HOST, port=PORT)

I appreciate the future help! :-)

[MOD: added ```python formatting -cf]

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 59,232 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 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!!!

Jay Reyes
Jay Reyes
Python Web Development Techdegree Student 15,935 Points

Chris Freeman so:

app = Flask(__name__)

... is abstractly setting the name of the Flask instance to app? And we want this for our secret key and decorators?

Then the Flask instance's name is actually set to __main__ once we run it interactively?