What Does __name__ in Python Do?

Problem scenario
What does the name syntax signify?

In the Python interpreter name keeps track of how a function or file is called. What does it signify exactly? Rather than explain this one in words, do the following:

1. Create foo.py with the following line (the name of the next file without its extension):

import bar

2. In the same directory as foo.py above, create bar.py with the following lines:

print ("Hello World from %s!" % __name__)

if __name__ == '__main__':
    print("Hello World again from %s!" % __name__)

3. Run these two commands and examine the output:

python foo.py

It prints out this:
Hello World from bar!

python bar.py

It prints out this:

Hello World from main!
Hello World again from

Leave a comment

Your email address will not be published. Required fields are marked *