Python Object-Oriented Python Inheritance Family Tree

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 23,332 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"

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