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

Joshua Richardson
954 PointsUnclear what's happening with Dunder Main
Hi, Related to my comment and request for help in the previous vid, I'm struggling to understand what's happening here - so much so that I'm not quite clear what questions to even ask. That stated, maybe these are good starting points:
- What is name?
- What is main?
- How do these work and why (again) are they important for us?
- Does the Dunder Main always go in the module file, or is it the script file (I'm not keeping track)?
Many thanks for any assistance. π
1 Answer

Travis Alstrand
Treehouse Project ReviewerHi there Joshua Richardson π
I'll try my best to break things down.
- What is
__name__
?
- In every Python file, there is a built-in variable called
__name__
. - When you run a file directly (like
python my_script.py
),__name__
becomes"__main__"
. - But if you import that file from another Python file,
__name__
becomes the name of the module (i.e., the filename without.py
).
- What does if
__name__ == "__main__"
mean?
It means:
"Only run this block of code beneath if this file is being run directly, not if it's being imported somewhere else."
This lets you write a file that can be:
- Run as a standalone script or
- Imported as a module without running everything automatically
- Why is this important?
Letβs say you have a file called math_tools.py
:
# math_tools.py
def add(a, b):
return a + b
print("Doing some math...") # <- This line always runs
if __name__ == "__main__":
print(add(2, 3)) # <- This only runs when math_tools.py is run directly
If you run:
python math_tools.py
You'll see:
Doing some math...
5
But if you import it from another file:
# another_script.py
import math_tools
and run this file, you'll only see:
Doing some math...
You wonβt see the print(add(2, 3))
partβbecause the file wasnβt the "main"
one being run. This allows for code to only be run in certain situations, great for testing things like that.
__name__
A built-in variable that tells you how a file is being run.
"__main__"
The value of __name__
when the file is run directly.
if __name__ == "__main__"
Run this code only when the file is run directly.
Where to put it? Usually in script files, but can be in modules for testing/debugging.
I hope this helps a bit.