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 trialAli Colak
2,192 PointsI 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?
1 Answer
Rachel Johnson
Treehouse TeacherHey Ali Colak , thanks for reaching out with your question! I'll try my best to answer!
Why does __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 __name__
and __main__
and their intricacies from the Python Docs!
Ali Colak
2,192 PointsAli Colak
2,192 PointsI see, so it's like a validation tool to see which file is running & evaluates accordingly! So when it's directly run from the file the name == main is in, it'll evaluate to true, otherwise it'll drag in the original actual file name to keep it from running the extra lines. This is really cool haha. Thank you so much Rachel!!