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 trial

Python Conditional Check

Watched this video twice and i still dont get it

Dunder main

4 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

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

Darcie Kutryk
Darcie Kutryk
2,129 Points

This 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.

  • It makes sense that app = __name__ in the second_app.py module.
  • It makes sense to run the second_app.py with the print display of "Hello from second_app.py"
  • "Hello from app." is printed, which tells me the conditional loop in app.py was executed, but how if we're operating in the second_app.py module where app != '__main__'

Can anyone point out what I'm missing?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,454 Points

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

One 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.

Yeah this one really skipped a lot of the explanation and didn't explain itself properly...

Thank you, ill go back to it again