Skip to main content

Command Palette

Search for a command to run...

Python: if __name__ == "__main__"

2 min read to finally understand

Updated
2 min read

Concept 1: Dunder-methods

In Python, everything is an object with meta properties. These meta properties are called “dunder”-methods, because they have leading and trailing double underscores. Even scripts themselves have dunder-methods.

Below is my_script.py

print(__file__)

__file__ is the script’s file location. This would print …/my_script.py

Concept 2: Importing in Python

In Python, scripts sitting in the same directory (folder) can import from one another. Let’s pretend I have two files: core.py and helpers.py. The core.py file is what’s ran when I want to start my program.

# Core.py
from helpers import get_data

data = get_data()
print(data)
# Helpers.py
def get_data():
    return [1, 2, 3]

print(“Interesting!”)

Combining concepts

So what should print if I ran core.py? Surprisingly, you would print

[1, 2, 3]
Interesting!

But why? My core.py doesn’t have a print("interesting!") statement, but it still prints?

This is because imported scripts execute completely, just like the script you ran. How do I stop this?

When you execute a script, it sets its own dunder-method __name__ to __main__. Now we can include a line in our script that basically says "if this script is being ran, run this code. If not, do nothing”

Here’s how you would refactor core.py

# Core.py
from helpers import get_data

if __name__ == "__main__":
    data = get_data()
    print(data)

TLDR!

Scripts are ran in full when imported. So if you plan on running the script, be sure to include the if __name__ == "__main__": so you can still import out of it from another script :)

J
Justin W4y ago

Very helpful, thank you Josh 🤗

1