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 trialArcee Palabrica
8,100 PointsThe if __name__ == '__main__':
Anyone who can clarify what if __name__ == '__main__':
is all about please? Appreciate it thanks guys. :)
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsGood question.
When a Python module is imported, the __name__
attribute is set to the name of the module. See docs on import related module attributes.
If, however, "A moduleβs __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.
" See __main__
in the docs.
Post back if you need more help. Good luck!!!
Claudio Paladini
13,403 PointsClaudio Paladini
13,403 Pointswhy do we need to verify that it is not being imported?
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsGood question! Code will fall roughly into three categories:
The top-most module called starts all execution and will be contain the last code run before execution stops. The mechanism above allows a way to specify code that will only execute at the top-most level.
It is not a requirement that this coding idiom is used, but this code allows a module to operate as a stand-alone program and to be imported into other modules without interfering with the other module's design if the other module intends to be a higher level top-most module.
As an example, say you create a module with many useful functions and classes that others may wish to import into their projects. However, if your module is called directly, you would like the module to launch an interactive prompt for the user to use your module on a command line interface. Others may not want the interactive interface to be active within their project, so this mechanism controls the two cases.
Post back if you have more questions. Good luck!!!