DEV Community

Mark Harless
Mark Harless

Posted on

if __name__ == __main__:

if __name__ == __main__:
  # some code
Enter fullscreen mode Exit fullscreen mode

The above code is something you'll see a lot when seeing other peoples' code in Flask. But what does this mean and why do people use it?

To start, let's create a new Python program and write this line of code in it:

# first_module.py

print(f"First module's name: {__name__}")

Enter fullscreen mode Exit fullscreen mode

What you will get in your console after running python first_module.py is:

First module's name: __main__
Enter fullscreen mode Exit fullscreen mode

So wtf is happening here?

Before Python runs any code it creates a few special variables. __name__ is one of those special variables. It then sets the __name__ variable equal to __main__. It does this because we ran a Python file directly to first_module.py when we entered python first_module.py.

Now, let's import first_module.py into a new module called second_module.py. Your first module should look exactly the same. In second_module.py just enter:

import first_module

print(f"Second module's name: {__name__}")
Enter fullscreen mode Exit fullscreen mode

Now, if you run python second_module.py you get the following in return:

First module's name: first_module
Second module's name: __main__
Enter fullscreen mode Exit fullscreen mode

The first module's __name__ is now set to first_module and the second module's __name__ is now set to __main__.

Are you picking up what I'm putting down here?

Whatever file we decide to run like python whatever.py, __name__ will be set to __main__ in whatever.py because that's where we ran the file directly!

if __name__ == __main__:
  # some code
Enter fullscreen mode Exit fullscreen mode

The reason why you see this line of code often is because it's checking to see if the current file was being run directly by Python or to another file. Sometimes you want code to only run when it's the main file.

Top comments (1)

Collapse
 
demianbrecht profile image
Demian Brecht