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 trialErik 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
Treehouse Moderator 28,720 PointsThis 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
Erik Embervine
Python Development Techdegree Student 2,442 Pointsthanks for your help Jeff :)