What does __name__ == '__main__' do in Python?

Sometimes you may come across a strange bit of Python code that looks like this:

# example.py

if __name__ == '__main__':
    # do something

Essentially, programmers use this to check if the Python module, in this case example.py, is being run as the main program. So for example, if you executed this file from the command line then that code block would run.

Let's add to the above code slightly to show what is happening.

# example.py

if __name__ == '__main__':
    print('Executed from the command line.')


Now if we run example.py from the command line, let's see what happens.

$ python example.py
Executed from the command line.

However, if you import example.py into the Python shell (or another module) the code inside the if statement will not run because the module has been imported and so the imported module's __name__ variable is not set to __main__.

$ python
>>> import example
>>> Done.

__name__ is a special attribute of the module that holds the name of the file being run. For example, if you execute example.py directly its __name__ will be set to the string '__main__'.