Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Using Databases in Python Meet Peewee Modeling

lindseyk
lindseyk
4,506 Points

Why 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

My 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]

lindseyk
lindseyk
4,506 Points

Ah, got it! Thanks, that makes more sense now!

willyraider
willyraider
6,550 Points

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

Reference

Edward Sapp
Edward Sapp
8,479 Points

It'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?