HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonTip

What does if __name__ == "__main__" do in Python?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
whatdoes__name____main__python

Problem

One of the most common lines of code you'll see in Python goes something like this:
While you might have seen this before, even used it a few times, it might not be clear what it does and how it works. Let's consider the following setup - two scripts, script1.py and script2.py. script2.py imports script1.py and calls a function from it.
```py title="script1.py"
def do_stuff:
print('Doing stuff')

Solution

if __name__ == "__main__":
  print("Hello, World!")


```py title="script1.py"
def do_stuff:
print('Doing stuff')
do_stuff()
py title="script2.py"
from script1 import do_stuff

Code Snippets

if __name__ == "__main__":
  print("Hello, World!")
What do you think happens when you run each of these scripts? Let's see.
As you can see, the function `do_stuff` is called twice when we run `script2.py`. This is because when we import a module, **Python executes all the code in the module**. So, when we import `script1.py` in `script2.py`, the function `do_stuff` is called once. Then, when we call `do_stuff` again, it's called a second time.

How do we fix this? By adding the `if __name__ == "__main__"` check in `script1.py`. This directive checks if the script is being **run directly**, or if it's being **imported**. If it's being run directly, the code inside the `if` block is executed, otherwise it's not.

Context

From 30-seconds-of-code: what-does-if-name-main-do

Revisions (0)

No revisions yet.