Short Answer

It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:

  • If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import time and using the second script's command line arguments. This is almost always a mistake.

  • If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.

Long Answer

To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.

Whenever the Python interpreter reads a source file, it does two things:

  • it sets a few special variables like __name__, and then

  • it executes all of the code found in the file.

Let's see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.

Code Sample

Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

Special Variables

When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.

When Your Module Is the Main Program

If you are running your module (the source file) as the main program, e.g.

python foo.py

the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

When Your Module Is Imported By Another

On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:

# Suppose this is in some other main program.
import foo

The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

Executing the Module's Code

After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.

Always

  1. It prints the string "before import" (without quotes).

  2. It loads the math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. It prints the string "before function_a".

  2. It executes the def block, creating a function object, then assigning that function object to a variable called function_a.

  3. It prints the string "before function_b".

  4. It executes the second def block, creating another function object, then assigning it to a variable called function_b.

  5. It prints the string "before __name__ guard".

Only When Your Module Is the Main Program

  1. If your module is the main program, then it will see that __name__ was indeed set to "__main__" and it calls the two functions, printing the strings "Function A" and "Function B 10.0".

Only When Your Module Is Imported by Another

  1. (instead) If your module is not the main program but was imported by another one, then __name__ will be "foo", not "__main__", and it'll skip the body of the if statement.

Always

  1. It will print the string "after __name__ guard" in both situations.

Summary

In summary, here's what'd be printed in the two cases:

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

Why Does It Work This Way?

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.

Food for Thought

  • Question: Can I have multiple __name__ checking blocks? Answer: it's strange to do so, but the language won't stop you.

  • Suppose the following is in foo2.py. What happens if you say python foo2.py on the command-line? Why?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
  • Now, figure out what will happen in foo3.py (having removed the __name__ check):
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
  • What will this do when used as a script? When imported as a module?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")
    
print("before __name__ guard")
if __name__ == "__main__":
    bar()
print("after __name__ guard")
Answer from Mr Fooz on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ __main__.html
__main__ โ€” Top-level code environment โ€” Python 3.14.6 ...
Usually, this is the name of the Python file itself without the .py extension: >>> import configparser >>> configparser.__name__ 'configparser' If the file is part of a package, __name__ will also include the parent packageโ€™s path: >>> from concurrent.futures import process >>> process.__name__ 'concurrent.futures.process' However, if the module is executed in the top-level code environment, its __name__ is set to the string '__main__'.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ python-main-function
How to Use the Python Main Function | DigitalOcean
March 19, 2026 - The if __name__ == "__main__": guard keeps top-level code from running on import, which makes scripts testable and avoids side effects when the file is used as a module. In Python there is no built-in โ€œmainโ€ that the interpreter runs. The Python main function is a convention: you define ...
Discussions

Understanding the main method of python - Stack Overflow
I am new to Python, but I have experience in other OOP languages. My course does not explain the main method in python. Please tell me how main method works in python ? I am confused because I am More on stackoverflow.com
๐ŸŒ stackoverflow.com
How does if __name__ == โ€œ__main__โ€ work? I've tried to look at so many sources but my brain just doesn't get it.
means code under that if name bla bla will only run WHEN that script is run directly. NOT when it's called as an import. (when importing all the code will run.. UNLESS it's under one of them if __name__ blocks) More on reddit.com
๐ŸŒ r/learnpython
24
42
June 16, 2023
What does def main mean in Python?
There's nothing special about a main function, its the same as any other function just with the name "main". In some other programming languages a main function is required to start the program, but not in python. But many programmers still use "main" as the program start point just because it makes sense to them. More on reddit.com
๐ŸŒ r/learnpython
37
61
September 30, 2024
Python Etiquette: calling functions

There is a maximum to the amount of linked function calls as this could cause a stack overflow. Not that you will easily reach that with this example, it's more of something to think about when you design program flow.

My preference is to do a regular step-by-step approach:

def main():
pic = download_pic(x)
pic = load_pic(pic)
result = process_pic(pic)
More on reddit.com
๐ŸŒ r/learnpython
8
3
December 9, 2015
Top answer
1 of 16
9054

Short Answer

It's boilerplate code that protects users from accidentally invoking the script when they didn't intend to. Here are some common problems when the guard is omitted from a script:

  • If you import the guardless script in another script (e.g. import my_script_without_a_name_eq_main_guard), then the latter script will trigger the former to run at import time and using the second script's command line arguments. This is almost always a mistake.

  • If you have a custom class in the guardless script and save it to a pickle file, then unpickling it in another script will trigger an import of the guardless script, with the same problems outlined in the previous bullet.

Long Answer

To better understand why and how this matters, we need to take a step back to understand how Python initializes scripts and how this interacts with its module import mechanism.

Whenever the Python interpreter reads a source file, it does two things:

  • it sets a few special variables like __name__, and then

  • it executes all of the code found in the file.

Let's see how this works and how it relates to your question about the __name__ checks we always see in Python scripts.

Code Sample

Let's use a slightly different code sample to explore how imports and scripts work. Suppose the following is in a file called foo.py.

# Suppose this is foo.py.

print("before import")
import math

print("before function_a")
def function_a():
    print("Function A")

print("before function_b")
def function_b():
    print("Function B {}".format(math.sqrt(100)))

print("before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("after __name__ guard")

Special Variables

When the Python interpreter reads a source file, it first defines a few special variables. In this case, we care about the __name__ variable.

When Your Module Is the Main Program

If you are running your module (the source file) as the main program, e.g.

python foo.py

the interpreter will assign the hard-coded string "__main__" to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when run as the main program.
__name__ = "__main__" 

When Your Module Is Imported By Another

On the other hand, suppose some other module is the main program and it imports your module. This means there's a statement like this in the main program, or in some other module the main program imports:

# Suppose this is in some other main program.
import foo

The interpreter will search for your foo.py file (along with searching for a few other variants), and prior to executing that module, it will assign the name "foo" from the import statement to the __name__ variable, i.e.

# It's as if the interpreter inserts this at the top
# of your module when it's imported from another module.
__name__ = "foo"

Executing the Module's Code

After the special variables are set up, the interpreter executes all the code in the module, one statement at a time. You may want to open another window on the side with the code sample so you can follow along with this explanation.

Always

  1. It prints the string "before import" (without quotes).

  2. It loads the math module and assigns it to a variable called math. This is equivalent to replacing import math with the following (note that __import__ is a low-level function in Python that takes a string and triggers the actual import):

# Find and load a module given its string name, "math",
# then assign it to a local variable called math.
math = __import__("math")
  1. It prints the string "before function_a".

  2. It executes the def block, creating a function object, then assigning that function object to a variable called function_a.

  3. It prints the string "before function_b".

  4. It executes the second def block, creating another function object, then assigning it to a variable called function_b.

  5. It prints the string "before __name__ guard".

Only When Your Module Is the Main Program

  1. If your module is the main program, then it will see that __name__ was indeed set to "__main__" and it calls the two functions, printing the strings "Function A" and "Function B 10.0".

Only When Your Module Is Imported by Another

  1. (instead) If your module is not the main program but was imported by another one, then __name__ will be "foo", not "__main__", and it'll skip the body of the if statement.

Always

  1. It will print the string "after __name__ guard" in both situations.

Summary

In summary, here's what'd be printed in the two cases:

# What gets printed if foo is the main program
before import
before function_a
before function_b
before __name__ guard
Function A
Function B 10.0
after __name__ guard
# What gets printed if foo is imported as a regular module
before import
before function_a
before function_b
before __name__ guard
after __name__ guard

Why Does It Work This Way?

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .py file that can be both used by other programs and/or modules as a module, and can also be run as the main program itself. Examples:

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

Beyond those examples, it's elegant that running a script in Python is just setting up a few magic variables and importing the script. "Running" the script is a side effect of importing the script's module.

Food for Thought

  • Question: Can I have multiple __name__ checking blocks? Answer: it's strange to do so, but the language won't stop you.

  • Suppose the following is in foo2.py. What happens if you say python foo2.py on the command-line? Why?

# Suppose this is foo2.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo2 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
if __name__ == "__main__":
    print("m1")
    function_a()
    print("m2")
print("t2")
      
  • Now, figure out what will happen in foo3.py (having removed the __name__ check):
# Suppose this is foo3.py.
import os, sys; sys.path.insert(0, os.path.dirname(__file__)) # needed for some interpreters

def function_a():
    print("a1")
    from foo3 import function_b
    print("a2")
    function_b()
    print("a3")

def function_b():
    print("b")

print("t1")
print("m1")
function_a()
print("m2")
print("t2")
  • What will this do when used as a script? When imported as a module?
# Suppose this is in foo4.py
__name__ = "__main__"

def bar():
    print("bar")
    
print("before __name__ guard")
if __name__ == "__main__":
    bar()
print("after __name__ guard")
2 of 16
2216

When your script is run by passing it as a command to the Python interpreter,

python myscript.py

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run. Unlike other languages, there's no main() function that gets run automatically - the main() function is implicitly all the code at the top level.

In this case, the top-level code is an if block. __name__ is a built-in variable which evaluates to the name of the current module. However, if a module is being run directly (as in myscript.py above), then __name__ instead is set to the string "__main__". Thus, you can test whether your script is being run directly or being imported by something else by testing

if __name__ == "__main__":
    ...

If your script is being imported into another module, its various function and class definitions will be imported and its top-level code will be executed, but the code in the then-body of the if clause above won't get run as the condition is not met. As a basic example, consider the following two scripts:

# file one.py
def func():
    print("func() in one.py")

print("top-level in one.py")

if __name__ == "__main__":
    print("one.py is being run directly")
else:
    print("one.py is being imported into another module")
# file two.py
import one

print("top-level in two.py")
one.func()

if __name__ == "__main__":
    print("two.py is being run directly")
else:
    print("two.py is being imported into another module")

Now, if you invoke the interpreter as

python one.py

The output will be

top-level in one.py
one.py is being run directly

If you run two.py instead:

python two.py

You get

top-level in one.py
one.py is being imported into another module
top-level in two.py
func() in one.py
two.py is being run directly

Thus, when module one gets loaded, its __name__ equals "one" instead of "__main__".

๐ŸŒ
Python
docs.python.org โ€บ 3.9 โ€บ library โ€บ __main__.html
__main__ โ€” Top-level script environment โ€” Python 3.9.25 documentation
This document is for an old version of Python that is no longer supported. You should upgrade, and read the Python documentation for the current stable release. ... '__main__' is the name of the scope in which top-level code executes.
๐ŸŒ
Real Python
realpython.com โ€บ if-name-main-python
What Does if __name__ == "__main__" Do in Python? โ€“ Real Python
November 30, 2024 - Pythonโ€™s if __name__ == "__main__" idiom looks cryptic, but itโ€™s just a conditional statement built on a special variable. Developers use it to give one file two jobs without the two getting in each otherโ€™s way.
๐ŸŒ
Real Python
realpython.com โ€บ python-main-function
Defining Main Functions in Python โ€“ Real Python
December 21, 2023 - In this example, you can see that __name__ has the value '__main__', where the quote symbols (') tell you that the value has the string type. Remember that, in Python, there is no difference between strings defined with single quotes (') and double quotes (").
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-main-function
Python Main Function - GeeksforGeeks
August 9, 2024 - File1 __name__ = File1 File1 is being imported File2 __name__ = __main__ File2 is being run directly ยท As seen above, when File1.py is run directly, the interpreter sets the ... and when it is run through File2.py by importing, the __name__ variable is set as the name of the python script, i.e.
Find elsewhere
๐ŸŒ
Python
docs.python.org โ€บ 3.8 โ€บ library โ€บ __main__.html
__main__ โ€” Top-level script environment โ€” Python 3.8.20 documentation
September 8, 2024 - This document is for an old version of Python that is no longer supported. You should upgrade, and read the Python documentation for the current stable release. ... '__main__' is the name of the scope in which top-level code executes.
๐ŸŒ
Tutorial Teacher
tutorialsteacher.com โ€บ python โ€บ main-in-python
__main__ and __name__ in Python
As you can see, it still executes the same code because of addition.py being executed in the top-level scope __main__. Thus, value of the name allows the Python interpreter to determine whether a module is intended to be an executable script or not. If its value is main, the statements outside function definitions will be executed.
Top answer
1 of 4
233

The Python approach to "main" is almost unique to the language(*).

The semantics are a bit subtle. The __name__ identifier is bound to the name of any module as it's being imported. However, when a file is being executed then __name__ is set to "__main__" (the literal string: __main__).

This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:

#!/usr/bin/env python
from __future__ import print_function
import this, that, other, stuff
class SomeObject(object):
    pass

def some_function(*args,**kwargs):
    pass

if __name__ == '__main__':
    print("This only executes when %s is executed rather than imported" % __file__)

Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.

It's important to understand that all of the code above the if __name__ line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a print statement before the if __name__ line then it will print output every time any other code attempts to import that as a module. (Of course, this would be anti-social. Don't do that).

I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.

Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use __name__ == "__main__" to isolate a block of code which calls a suite of unit tests that apply to this module.

(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).

Summary: if __name__ == '__main__': has two primary use cases:

  • Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)
  • Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.

It's fairly common to def main(*args) and have if __name__ == '__main__': simply call main(*sys.argv[1:]) if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might def test_module() and calling test_module() in your if __name__ == '__main__:' suite.

  • (Ruby also implements a similar feature if __file__ == $0).
2 of 4
84

In Python, execution does NOT have to begin at main. The first line of "executable code" is executed first.

def main():
    print("main code")

def meth1():
    print("meth1")

meth1()
if __name__ == "__main__":main() ## with if

Output -

meth1
main code

More on main() - http://ibiblio.org/g2swap/byteofpython/read/module-name.html

A module's __name__

Every module has a name and statements in a module can find out the name of its module. This is especially handy in one particular situation - As mentioned previously, when a module is imported for the first time, the main block in that module is run. What if we want to run the block only if the program was used by itself and not when it was imported from another module? This can be achieved using the name attribute of the module.

Using a module's __name__

#!/usr/bin/python
# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Output -

$ python using_name.py
This program is being run by itself
$ python
>>> import using_name
I am being imported from another module
>>>

How It Works -

Every Python module has it's __name__ defined and if this is __main__, it implies that the module is being run standalone by the user and we can do corresponding appropriate actions.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ usage-of-__main__-py-in-python
Usage of __main__.py in Python - GeeksforGeeks
April 28, 2025 - The output will be - So what happens when we execute the command. Python looks for a file named __main__.py to start its execution automatically. If it doesn't find it will throw an error else it will execute main.py and from the code, you can ...
๐ŸŒ
Substack
mostlypython.substack.com โ€บ mostly python โ€บ do you really need a main() function?
Do you really need a main() function? - Mostly Python
September 26, 2023 - When a file is imported, Python runs all the code in the file. That means if you import the file hello_world.py, youโ€™ll see the output of the print() call: ... But if you import the version that used an if __name__ == "__main__" block, the print() call wonโ€™t be executed:
๐ŸŒ
Gabormelli
gabormelli.com โ€บ RKB โ€บ Python_main()_Function
Python main() Function - GM-RKB
However, when a file is being executed then __name__ is set to "__main__" (the literal string: __main__). This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how does if __name__ == โ€œ__main__โ€ work? i've tried to look at so many sources but my brain just doesn't get it.
r/learnpython on Reddit: How does if __name__ == โ€œ__main__โ€ work? I've tried to look at so many sources but my brain just doesn't get it.
June 16, 2023 -

I've watched many videos over and over, read forums, and gone to w3schools but the explanation just seems like spaghetti to me and I lose what they mean (ive been studying python/programming for a few months). Can someone explain in the simplest way possible what it is for?

While on that note I also want to know why some people list variables as an underscore meaning they aren't to be used, why not just not declare the variable if you won't use it?

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what does def main mean in python?
r/learnpython on Reddit: What does def main mean in Python?
September 30, 2024 -

Hi, I just wanted someone to explain to me in a simple way what def main means in Python. I understand what defining functions means and does in Python but I never really understood define main, (but I know both def main and def functions are quite similar though). Some tutors tries to explain to me that it's about calling the function but I never understood how it even works. Any answer would be appreciated, thanks.

๐ŸŒ
Medium
medium.com โ€บ codex โ€บ what-is-name-main-in-python-c0c14b588c63
What is __name__ == โ€œ__main__โ€ in Python? | by Ishaan Gupta | CodeX | Medium
August 19, 2025 - If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value โ€œ__main__โ€. If this file is being imported from another module, __name__ will be set to the moduleโ€™s name.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ main-function
Python Main function
If we run helloworld.py from the command line, then it runs as a Python script. We can run the Python program using the following command: ... When we run the program as a script, the value of the variable __name__ is set to __main__.
๐ŸŒ
Medium
medium.com โ€บ @jordan.l.edmunds โ€บ how-to-main-like-a-boss-dcc6dfb16223
How to __main__ like a boss. Using entry points in your pythonโ€ฆ | by Jordan Edmunds Chetty, PhD | Medium
December 2, 2023 - For example, suppose you are writing a command-line tool to square a numbe. I put the parsing of command-line options inside the __main__ entry point directly, and then pass those into the main() function as arguments:
๐ŸŒ
Built In
builtin.com โ€บ articles โ€บ name-python
What Does โ€œIf __name__ == โ€˜__main__โ€™โ€ Do in Python? | Built In
__name__ is a special variable in Python. โ€œIf __name__== โ€˜__main__โ€™โ€ is a conditional statement that tells the Python interpreter under what conditions the main method executes.