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.
Ali Colak1,398 Points
I still don't understand how the Dunder Main works, I understand the __name__ equals the __main__, but why?
Why does Dunder Main work the way it does? / Why does the if statement prove false if the second (app.py) file is run?
Rachel JohnsonTreehouse Staff
Hey Ali Colak , thanks for reaching out with your question! I'll try my best to answer!
__name__ == "__main__"? This is something that evaluates to true if the file is being run directly. It will evaluate to false if it's not being run directly, such as if it's being imported into another module.
__name__ is equal to
__main__ if the file is being run directly.
The basic use-case is to run code if and only if a Python file is the one that's being run directly. A developer may use Dunder Main to store some tests in an imported module so they can be tested in a smaller environment.
So in the video, when we run
app.py, the Dunder Main block of
dm.py is never run.
dm.py is not being called to run directly (it's only being imported).
You can read a lot more about the use of
__main__ and their intricacies from the Python Docs!