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 triallindseyk
4,506 PointsWhy is __name__==__main__ a needed condition?
Why is it that we only want this script to run if it is not imported? I can understand the concept of name ==main , but would appreciate more clarity on when it is necessary to use (or preferred, if that is the case). Thank you!
3 Answers
William Laub
7,793 PointsMy understanding is that it may be desirable to use the script both as a script and as a library. The __name__ == '__main__'
check allows you to add code that will run when you run the script but will not run when you import the script.
In this case, the script contains database stuff you might want to use elsewhere, but you might not want to connect to the database and create tables right away in your other script. Without the __name__ == '__main__'
check, that connection code would be run as soon as you import the file into your other project.
[MOD fixed formatting. -cf]
willyraider
6,550 PointsI had to look this up. Here is a nice explanation from Dave Angel:
name attribute exists in all modules, and is simply the file name that was imported (without path and such). And it's filled in for the script as well, but given a unique value, regardless of the script's filename.
The PURPOSE, however, is to let programs tell whether a particular source file was loaded as a script, or imported as a module. It's a common paradigm for modules to do self-testing when the source is loaded as a script. But you don't want that self-test code to be live when some other program uses the module.
Edward Sapp
8,479 PointsIt's explained here, and it seems everyone above has explained it pretty well: https://docs.python.org/3/library/__main__.html
However...I don't understand why we want this? All the explanations say it can tell whether a source file was "loaded as a script, or imported as a module." Why is that significant? Could someone give a clear example of why we want this, i.e. how not including this line would mess things up?
Vittorio Somaschini
33,371 PointsVittorio Somaschini
33,371 Points(comment changed into answer) ;)
lindseyk
4,506 Pointslindseyk
4,506 PointsAh, got it! Thanks, that makes more sense now!