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 Object-Oriented Python Inheritance Family Tree

i donr understande __name__


1 Answer

Jeff Muday
Jeff Muday
Treehouse Moderator 28,716 Points

__name__ is a special variable in Python. The script file that is being directly executed will have the value of its __name__ variable set to __main__

The special signifcance of the variable is that it allows the program to make choices based on what module was executed at the top level.

If a script file is imported and you print the value of __name__ it will have a different value. In fact, the value will match the name under which it is imported.

Here's a quick demo (note I am using Python 2.x, but Python 3.x will work the same except you will need parenthesis around the print arguments).

Suppose you have a single line Python file, called "script1.py"

print "executing script1 __name__ =  " + __name__

When you execute it with the Python interpreter, it will print out the following.

executing script1 __name__ = __main__

So far so good...

Now let's create another script called "script2.py"


import script1

print "executing script2 __name__ =  " + __name__

This will import script1, but you get something interesting.

executing script1 __name__ = script1
executing script2 __name__ = __main__

When script1 is imported it executes, but its special __name__ is "script1". But then script2.py gets to its print statement and prints out that its special __name__ is __main__.

This may seem confusing now, but you will see a repeating code pattern usually at the "bottom" of the execution module where the module checks if it's name is main and executes a code block. This is a good practice to implement and if you repeat it frequently it will become second nature!

if __name__ == '__main__':
    ... execute your code block here ...

Good luck with your Python journey!!