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 Executable

Erik Embervine
seal-mask
.a{fill-rule:evenodd;}techdegree
Erik Embervine
Python Development Techdegree Student 2,442 Points

__name__

so does the name variable get assigned the "main" value if the code the python interpreter is currently reading happens to be read from the current file that was called (as opposed to any other file the current script references, i.e. imported module files)?

2 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

This can be easily tested.

The magic __name__ attribute of the module takes on the value of the file name without the .py extension. But the __name__ attribute of the running program always has the value "__main__"

# first_module.py
import second_module
print("First Module: running the code in first_module.py")
print("First Module: the magic name is " + __name__ )
print( "First Module: importing Second Module: the magic name is " + second_module.__name__ )
# second_module.py
print("Second Module: running the code in second_module.py")
print("Second Module: the magic name is " + __name__ )

Note, when your import the second_module.py the code inside that runs first because it is imported and then the first_module.py is run.

C:\> python first_module.py
Second Module: running the code in second_module.py
Second Module: the magic name is second_module
First Module: running the code in first_module.py
First Module: the magic name is __main__
First Module: importing Second Module: the magic name is second_module