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

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

Claudio Paladini
Claudio Paladini
11,675 Points

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

Chris Freeman
Chris Freeman
Treehouse Moderator 68,064 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!!!