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 trialAizah Sadiq
2,435 PointsConditional check
I don't understand what the purpose of dunder main is. I don't understand how it works and how is it that when he imported the code from app.py to second_app.py. It ran differently than when he used the if statement. Thirdly what does this statement mean/do
app.print_hello()
3 Answers
Jeff Muday
Treehouse Moderator 28,720 PointsDefinitely a good question/answer to know for a potential interview. I recommend you set up a couple of python modules to test this out. People who are primarily JavaScript or PHP programmers might get tripped up, but a Pythonista will smile and tell them:
__name__
(aka dunder name) is a special variable which holds the identity of the module being executed.__main__
is a string VALUE that__name__
takes on ONLY if it is the was the file executed. Otherwise, it will have the name of the module/import.
Often the statement at the end of a main app module will have the following conditional block:
if __name__ == '__main__':
# execute the block ONLY if this is the main module.
execute_the_app()
I recommend you try this experiment...
Suppose we had two modules, one called "app.py", the other called "module.py". app.py will be the one we run with Python and module will run when it is imported by app.py
app.py
import module
print("Hello from app.py")
print("app.py reports its name: ", __name__)
module.py
print("Hello from module.py")
print("module.py reports its name: ", __name__)
Then we finally run the file (with Python 3)
treehouse:~/workspace$ python app.py
Hello from module.py
module.py reports its name: module
Hello from app.py
app.py reports its name: __main__
When programming you can isolate some code in a module and ONLY run it when it is the main executable module, and not run it when it is a support module. Good luck with your Python journey!
Hydar Omar
1,582 PointsWhat an amazing explanation thank you.
Scott Miller
Python Development Techdegree Student 7,655 PointsWhoa, I'm pretty sure none of this was in the video!