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 Using Databases in Python Meet Peewee Modeling

Arcee Palabrica
Arcee Palabrica
8,100 Points

The if __name__ == '__main__':

Anyone who can clarify what if __name__ == '__main__': is all about please? Appreciate it thanks guys. :)

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

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

why do we need to verify that it is not being imported?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Good question! Code will fall roughly into three categories:

  • code that defines objects that's are put into the namespace to be called later for execution
  • code that should execute immediately when a module is imported
  • code that should only run when the module being imported it the top-most module called.

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