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 Executable

Ali Colak
Ali Colak
1,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?

1 Answer

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Staff

Hey 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
Ali Colak
1,398 Points

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