if __name__ == __main__:

harlessmark

Mark Harless

Posted on April 12, 2020

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.

💖 💪 🙅 🚩
harlessmark
Mark Harless

Posted on April 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024