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 trialOlebogeng Nkele
3,018 PointsWatched this video twice and i still dont get it
Dunder main
4 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsWhen a file is imported, all of the code is executed upon import. If there is code that is not in a function or class definition it will execute. This may be what you want if the module is run directly, but what if you don't want some code to execute on imports.
In normal importing, the __name__
attribute of a module is set to the file name. For the file "app.py", the attribute __name__
would be set to "app". To differentiate which module is the "top" module, that is the one that is executed and is importing all the other modules, the python convention is to set the __name__
attribute of a module to "__main__".
With this change, the statement if __name__ == "__main__":
will execute the code block only if it was the top level module and not if it was imported into another module.
Post back if you need more help. Good luck!!
mijurg
16,044 PointsOne of the worst videos i have seen on treehouse. This is disappointing that we pay for such content. It is important concept , but to explain it so bad is a shame and it should be remade in my opinion. This makes students feel stupid and doubt themselves, when in fact this is not easy to grasp and it should be created with more responsibility.
Ryan Hartigan
3,426 PointsYeah this one really skipped a lot of the explanation and didn't explain itself properly...
Olebogeng Nkele
3,018 PointsThank you, ill go back to it again
Darcie Kutryk
2,129 PointsDarcie Kutryk
2,129 PointsThis explanation makes sense (Thanks, Chris), but I still can't figure out why the interpreter prints "Hello from app" when you run python second_app.py.
app = __name__
in the second_app.py module.app != '__main__'
Can anyone point out what I'm missing?
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsLater in the video, Ken adds into second_app.py the line:
app.print_hello()
Which explicitly calls the function in app.py.
Post back if you need more help. Good luck!!!