What Does if name == "main" do in Python?

Better Stack Team
Updated on January 24, 2023

The if __name__ == "main" is a guarding block that is used to contain the code that should only run went the file in which this block is defined is run as a script. What it means is that if you run the file as a script the `__name__variable will be equal to'main'`.

Let’s look at an example:

mylib.py:

def say_hi():
    print('hi from the function')

if __name__ == 'main':
    print('the main block is being executed')
    say_hi()
Copied!

In the example above, we have defined a say_hi function that will simply say hi when called. Then there is a guarded block with the if __name__ == 'main': statement.

If you run the script in the console lie this:

python3 mylib.py
Copied!

The output will be the following:

Output:
the main block is being executed
hi from the function
Copied!

But if you include the mylib.py file in some other python file and run that file as a script, you will see that the guarded block will not be executed.

other.py:

import say_hi from mylib

say_hi()
Copied!
Output:
hi from the function
Copied!
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack