Whenever you’ve seen the code of another Python developer, you’ve probably come across the if __name__ == “__main__” phrase. Because it’s so common, of course. It’s possible that you’ve used the conditional statement if __name__ == “__main__” in your own scripts. But were you proper in its application?
If you’re familiar with programming in a language of the C-family like Java, you might be wondering if this construct is merely an awkward add-on to the more conventional practise of calling a main() function.
Python’s if __name__ == “__main__” idiom is, syntactically speaking, no different from any other conditional block.
:
1if __name__ == "__main__":
2 ...
If the test in line 1 returns True, Python will run the code in the indented block starting at line 2. The ellipsis in the preceding code sample stands in for the actual logic that you would write in the conditional block ( … ).
If the if __name__ == “__main__” idiom isn’t special in any way, why does it give off the wrong impression, and why does it continue to be a topic of debate among Python programmers?
You’ve come to the correct spot if the idiom is still a bit mysterious to you and you’re still not quite clear on what it means, why you would want it, and when to apply it. This guide will teach you all you need to know about the if __name__ == “__main__” idiom in Python, from its actual purpose in the language to a suggested shortcut for using it in the future.
it.
In Short: It Allows You to Execute Code When the File Runs as a Script, but Not When It’s Imported as a Module
For all intents and purposes, the block of code that you initiate with if __name__ == “__main__” is where you should put any code that you want to run only when the file is being executed as a script.
You’ll understand in a second. Thus far, let’s assume you have the following:
file:
1# echo.py
2
3def echo(text: str, repetitions: int = 3) -> str:
4 """Imitate a real-world echo."""
5 echoed_text = ""
6 for i in range(repetitions, 0, -1):
7 echoed_text += f"{text[-i:]}\n"
8 return f"{echoed_text.lower()}."
9
10if __name__ == "__main__":
11 text = input("Yell something at a mountain: ")
12 print(echo(text))
By displaying less and fewer of the last letters of the input text, the echo() function you construct here behaves like a real-world echo.
The phrase if __name__ == “__main__” is used on lines 10–12 below that. On line 10, we have the if statement: if __name__ == “__main__”. Lines 11 and 12 are indented because here is where you take user input and send it to echo(). When you run the script echo.py from the command line, these two lines will be carried out.
line:
$ python echo.py
Yell something at a mountain: HELLOOOO ECHOOOOOOOOOO
ooo
oo
o
.
The expression __name__ == “__main__” evaluates to True if the file is executed as a script by handing the file object to the Python interpreter. When the if statement is evaluated, Python takes the user’s input and executes the function echo().
Give it a try and see what you think! All the necessary code files for this lesson may be downloaded from the following link:
Nevertheless, the nested code will not be executed if you import echo() in a different module or a console session.
run:
>>>
>>> from echo import echo
>>> print(echo("Please help me I'm stuck on a mountain"))
ain
in
n
.
Because you won’t be requiring input from the user, you may safely use echo() inside the context of another script or interpreter session. Because of an unwanted side effect caused by running input(), importing echo would cause your code to break.
By enclosing your script’s usage-specific code with an if __name__ == “__main__” idiom, you may prevent imported modules from triggering code that isn’t necessary for the script’s operation.
You may accommodate a variety of use cases by nesting code beneath if __name__ == “__main__.”
cases:
-
Script:
When run as a script, your code prompts the user for input, calls
echo()
, and prints the result. -
Module:
When you import
echo
as a module, then
echo()
gets defined, but no code executes. You provide
echo()
to the main code session without any side effects.
If you use the if __name__ == “__main__” technique, you may use echo() directly from the command line without having to go via the main() function.
Now you know! You’ve effectively summarised the key points here. There is still more to learn, and paying attention to certain nuances can help you get a more complete comprehension of both this code and Python in general.
If you’re curious about the name-main idiom, which will be used throughout this guide, read on!
short.
How Does the Name-Main Idiom Work?
The idiom boils down to a conditional statement in which it is determined whether the value of a given variable is equivalent to the text “__main__.”
:
-
If the
__name__ == "__main__"
expression is
True
, then the indented code following the conditional statement executes. -
If the
__name__ == "__main__"
expression is
False
, then Python skips the indented code.
When does __name__ equal “__main__”? This is the situation when you execute your Python file as a script from the command line, as you saw in the previous section. That should be plenty for the vast majority of practical applications, but maybe you need more detail.
Initialization of Global Variables in Python
If the Python interpreter executes your code in the top-level code environment, the __name__ of the module will be “__main__.”
Top-level code refers to the first Python module called by the user. It is considered “top-level” since it is responsible for importing all other required modules. ( Original)
For clarity, you’ll build up a simple example. Create a new Python file with the name namemain.py and include the following line of code:
code:
# namemain.py
print(__name__, type(__name__))
One line of code is all that’s in your new file; it simply outputs the current value and type of the global variable __name__.
Bring up a terminal and execute the Python file as a script.
:
$ python namemain.py
__main__ <class 'str'>
The result tells you that the value of __name__ is the Python string “__main__” if you execute your file as a script. It is important to remember that “__main__” is always substituted for “__name__” in the top-level code environment. As you saw above, the top-level code environment is often a module sent as a file argument to the Python interpreter. The top-level code, however, may also be made up of a few other things.
environment:
- The scope of an interactive prompt
-
The Python module or package passed to the Python interpreter with
the
-m
option
, which stands for
module
- Python code read by the Python interpreter from standard input
-
Python code passed to the Python interpreter with
the
-c
option
, which stands for
command
Check out the Python reference manual for additional information on the top-level coding environment and all the available configurations. Each of those items is followed by a little code sample in the docs to demonstrate what it means in practise.
You can now predict what will happen to __name__ in the top-level code environment.
Yet, a conditional statement can only provide varying outcomes if the condition is given several opportunities to assess. When this occurs, what happens to the value of __name__, and how is code executed?
If you import a module, its contents will not be executed in the main program’s context. If this occurs, Python will save the module’s name in the __name__ variable.
To experiment with this, fire up a Python prompt and import the namemain.py file.
module:
>>>
>>> import namemain
namemain <class 'str'>
The import of namemain.py causes Python to run the code found in the file’s global namespace, which in this case is print( name__, type( name__)).
On the other hand, the __name__ of the module has a new value here. It’s a pointer to the string “namemain,” which is the module’s actual name. Any file with Python code in it may be imported as a module, and Python will execute that code when you do so. The name of a Python file without its extension is the module’s name ( .py ).
Confirm inside your interpreter session what you just learned: that the value of __name__ is always “__main__” in the top-level code environment. Verify the origin of the string “namemain,”
from:
>>>
>>> __name__
'__main__'
>>> namemain.__name__
'namemain'
The string “__main__” is assigned to the global variable __name__, whereas the string “namemain” is assigned to the imported module’s. name__ variable. Recall that the Python script you run and from which you import additional modules is often the top-level code environment. The top-level code environment is typically a script run, but this example shows that an interpreter session may serve the same purpose.
You may expect one of two values for __name__ now, depending on the context in which it is used.
lives:
-
In
the top-level code environment
, the value of
__name__
is
"__main__"
. -
In an
imported module
, the value of
__name__
is the
module’s name
as a string.
Python’s adherence to these standards makes it possible to determine whether or not a given module is being executed in the privileged context of the Python interpreter. To do this, you will use a conditional statement to examine the value of __name__, which will lead you back to the name-main connection.
idiom:
# namemain.py
print(__name__, type(__name__))
if __name__ == "__main__":
print("Nested code only runs in the top-level code environment")
With this if/else statement, you may restrict the module’s code to only be executed when the top-level code environment is being used.
Copy and paste the preceding code snippet into namemain.py, which is a script file, and execute it once.
more:
$ python namemain.py
__main__ <class 'str'>
Nested code only runs in the top-level code environment
Both calls to print() will be carried out when your code is executed in script form.
Then, launch a fresh session of the interpreter and import namemain once as a module.
more:
>>>
>>> import namemain
namemain <class 'str'>
Code contained beneath if __name__ == “__main__” is ignored when a file is imported as a module.
Because you now understand the inner workings of the name-main idiom in Python, you may be wondering when and how you should employ it.
it!
When Should You Use the Name-Main Idiom in Python?
By using this idiom, you can make your script file usable in two ways: either as a standalone programme or as an importable module. When your script requires input from the user, this feature might come in handy.
When you ran the script version of echo.py in the first part of this article, you used the name-main idiom in conjunction with input() to gather input from the user. It is an excellent illustration of the name-main idiom in action!
It’s also possible to get input from the user in other methods, including via the command line. With sys.argv and the name-main combination, for instance, you might make a simple Python script executable from the command line.
idiom:
1# echo.py
2
3import sys
4
5def echo(text: str, repetitions: int = 3) -> str:
6 """Imitate a real-world echo."""
7 echoed_text = ""
8 for i in range(repetitions, 0, -1):
9 echoed_text += f"{text[-i:]}\n"
10 return f"{echoed_text.lower()}."
11
12if __name__ == "__main__":
13 text = " ".join(sys.argv[1:])
14 print(echo(text))
You modified the code in echo.py so that the text is supplied as arguments to the command rather than gathered using input().
line:
$ python echo.py HELLOOOOO ECHOOOO
ooo
oo
o
.
Python stores all inputs in sys.argv, a string array with an arbitrary length. If there is a whitespace character between words, then those words are treated as independent arguments.
Inserting the code that processes input from the user into the name-main idiom creates a second entry point for the script.
Create a file named __main .py to serve as the entry point for the package you’re working on. When you execute your package with the -m option in Python, this file serves as an entry point.
:
$ python -m venv venv
Code written in a file named __main .py is executed when a virtual environment is created using the venv module, as shown above. When __main .py is used with the -m option with the module name venv, the
plugin for venv.
As venv is a package and not just a simple CLI script, it boots directly into its own __main .py file.
It’s worth noting that the name-main idiom has additional benefits, such as collecting user input, that come from layering code inside of it. Running unit tests on your functions from a dedicated testing module is safe since the nested code will not execute during module imports.
A testing module must import your module in order to perform tests on your code, which introduces the possibility of unintended consequences.
The name-main idiom in Python is useful for a variety of reasons, and you may find even more of them out in the real world. Yet, the most often proposed use case for is accumulating user input through standard input or the command-line.
it.
When Should You Avoid the Name-Main Idiom?
You now know when it is OK to use the name-main idiom, and you can go on to discovering the situations in which it is inappropriate. Python’s if __name__ == “__main__” statement is useful, but you may be surprised to realise that there are often more elegant ways to organise your code.
When writing a script that exercises both code functionality and tests, developers may use the name-main idiom to add test runs to the same file.
file:
# adder.py
import unittest
def add(a: int, b: int) -> int:
return a + b
class TestAdder(unittest.TestCase):
def test_add_adds_two_numbers(self):
self.assertEqual(add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
By executing your code in this fashion, you can also perform tests on it.
script:
$ python adder.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
As the file was executed as a script, the conditional statement evaluated to True, calling Python’s unittest.main(). Your little test suite completed its run successfully.
And yet, you didn’t introduce any unintended behaviour into the system by importing your code as a
module:
>>>
>>> import adder
>>> adder.add(1, 2)
3
You may still call the function you specified in the module after it has been imported. It is only when the module is executed at the top-level code that the unit test will be triggered.
This may be OK for very tiny files, but it is not recommended for use in most situations. Having both tests and production code in the same file is not recommended. Create a new file just for your testing. In most cases, a more structured code base is the result of following this guidance. Also, no unnecessary steps are taken, such as importing unittest into your main script file, when you use this method.
Some developers also resort to the name-main idiom to showcase the capabilities of their programmes.
do:
# echo_demo.py
def echo(text: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in range(repetitions, 0, -1):
echoed_text += f"{text[-i:]}\n"
return f"{echoed_text.lower()}."
if __name__ == "__main__":
print('Example call: echo("HELLO", repetitions=2)', end=f"\n{'-' * 42}\n")
print(echo("HELLO", repetitions=2))
Once again, importing the module won’t have any unintended consequences for your users. Echo demo.py also gives users a sneak peak at its inner workings when launched as a script.
functionality:
$ python echo_demo.py
Example call: echo("HELLO", repetitions=2)
------------------------------------------
lo
o
.
Such code executions are common in the name-main idiom, but there may be more effective methods to show off your app’s features. Provide thorough documentation for your work, including full docstrings with sample runs that may serve as doctests.
The first two instances illustrate two frequent, inefficient use of the name-main idiom. The name-main idiom should be avoided in a number of other contexts as well.
Python:
-
A pure script:
If you write a script that’s
meant
to be run as a script, then you can put your code execution into the global namespace without nesting it in the name-main idiom. You
can
use Python as a scripting language because it doesn’t enforce strong
object-oriented patterns
. You don’t have to stick to design patterns from other languages when you program in Python. -
A complex command-line program:
If you write a
larger
command-line application, then it’s best to create a separate file as your entry point. You then import the code from your module there instead of handling user input with the name-main idiom. For more complex command-line programs, you’ll also benefit from using the built-in
argparse
module
instead of
sys.argv
.
You could have even used the name-main idiom in one of these less-than-ideal contexts previously. Follow the links given if you’d want further information on how to write idiomatic Python in any of these cases:
links:
❌ Suboptimal Use Case | ✅ Better Alternative |
---|---|
Test code execution |
Create a dedicated testing module |
Demonstrate code |
Build project documentation and include examples in your docstrings |
Create a pure script |
Run as a script |
Provide a complex CLI program entry point |
Create a dedicated CLI module |
You may be wondering when and why the name-main idiom is not appropriate, but you now know better.
scenario.
In What Way Should You Include the Name-Main Idiom?
Python’s name-main idiom is just a conditional statement and can be used wherever you like, even multiple times, in the same file. Therefore, in most circumstances, you will place the name-main idiom at the end of your
script:
# All your code
if __name__ == "__main__":
...
Given that a Python script’s entry point is always the top of the file, the name-main idiom is placed at the very end of the script. Placing the name-main idiom at the end of a file ensures that all of your classes and functions are defined before Python evaluates the if statement. Python’s definition phase does not execute the code in a function or class body. To put it another way, you won’t see that code run unless you make a function or class call.
Multiple name-main idioms in a script are unusual, but not impossible. All import statements must go in the location specified by PEP 8, the Python style guide document:
Imports come first in a file, following any comments or documentation for the module but before any globals or constants defined by the module. ( Original)
This is why sys was imported at the very beginning of the echo.py code.
:
# echo.py
import sys
def echo(text: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in range(repetitions, 0, -1):
echoed_text += f"{text[-i:]}\n"
return f"{echoed_text.lower()}."
if __name__ == "__main__":
text = " ".join(sys.argv[1:])
print(echo(text))
Nevertheless, if you just want to import echo, you don’t have to import sys at all.
A second name-main idiom might be used to remedy this while still adhering to the style recommendations outlined in PEP 8. Rather of having to import sys every time, you can put all of your imports in one place at the start of the file by nesting the import of sys in a name-main idiom.
it:
# echo.py
if __name__ == "__main__":
import sys
def echo(text: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in range(repetitions, 0, -1):
echoed_text += f"{text[-i:]}\n"
return f"{echoed_text.lower()}."
if __name__ == "__main__":
text = " ".join(sys.argv[1:])
print(echo(text))
You’ve hidden the sys import within a name-main idiom. You may avoid importing sys while using echo as a module without having to remove the import line from the start of your project. While this configuration is not common, it is included here as an example of when it could be useful to use various name-main idioms inside the same file.
However readability is important, therefore it’s usually best to put the import statement first, without the second name-main idiom. When operating in a low-supply setting, however, the adage “second name, primary” might be useful.
Learned previously in the tutorial: the name-main idiom is used less often than one may think. The ideal solution for most of these scenarios is to include one of these tests as a last step in your script.
Last but not least, you may be wondering what instructions to provide within the if/then block. The Python manual provides helpful examples of how to use the name-main idiom correctly.
You may make your code more readable and error-free by minimising the number of statements in the block below if __name___ == ‘__main__’. ( Original)
Reduce the amount of jargon behind your username to a minimum. You should declare a new function whenever you need to nest more than one line of code under the name-main idiom.
calling the main() function
function:
# echo.py
import sys
def echo(text: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in range(repetitions, 0, -1):
echoed_text += f"{text[-i:]}\n"
return f"{echoed_text.lower()}."
def main() -> None:
text = " ".join(sys.argv[1:])
print(echo(text))
if __name__ == "__main__":
main()
The benefit of using this design pattern is that it results in succinct and readable code for the name-main idiom. Also, it allows you to use main() after importing your code as a module, which is useful for doing unit testing. Be aware that the definition of main() in Python differs from that in languages like Java and C. A common practise in Python is to refer to this function as main. You’re free to give the function whatever name you choose; as we’ve seen previously, it’s not even necessary.
The main() method serves as the program’s entry point in many other object-oriented languages. In such situation, your programme will fail unless you include the main() method, which is automatically called by the interpreter.
Based on everything you’ve read so far, the name-main idiom should be placed at the end of your script.
Instead of nesting numerous lines of code inside if __name__ == “__main__”, it’s preferable to rework the code into a main() function and then call that function from the conditional block using the name-main idiom.
Now that you know how to utilise the name-main idiom, you may be confused as to why the code appears more complicated than typical Python.
to.
Is the Idiom Boilerplate Code That Should Be Simplified?
If you’re used to object-oriented languages like Java or C, you might mistake Python’s name-main idiom for a clumsier version of those languages’ main() entry points.
Internet-comic-inspired meme (Image:
Michael Organsik)
This meme is hilarious and relevant, but it’s deceptive since it makes it seem like the name-main idiom is the same as the main() entry point function in other languages, while in fact they’re quite different.
The name-main idiom used by Python isn’t unique. It’s merely an if-then test. When you’re first getting started with Python and are accustomed to its short and beautiful syntax, it might appear a little mysterious. After all, the name-main idiom consists of a string that is also a dunder value and a dunder variable from the global namespace.
So, it’s not the same as the “main” entry point used in most other programming languages. The question is, what causes that appearance? You may have repeatedly copied or written the idiom while wondering why Python doesn’t provide a shorter syntax.
The Python-ideas mailing list, rejected PEPs, and the Python discussion forum are all good places to look for proposed changes to the language.
Several seasoned Pythonistas have argued that the idiom isn’t mysterious and shouldn’t be modified in these conversations, as you will see if you read a few of them. They provide a variety of
reasons:
-
It’s short:
Most suggested changes save only two lines of code. -
It has a limited use case:
You should only use it if you need to run a file both as a module as well as a script. You shouldn’t need to use it very often. -
It exposes complexity:
Dunder variables and function are a big part of Python once you
peek a bit deeper
. That can make the current idiom an entry point for learners that sparks curiosity and gives them a first look under the hood of Python’s syntax. -
It maintains backward compatibility:
The name-main idiom has been a de facto standard in the language for a long time, which means that changing it would break backward compatibility.
OK, you’ll just have to live with if __name__ == “__main__” for now. A clear and common term for it seems like it would be useful.
Please see the expanded part below for more background and some recommendations on how to discuss the name-main idiom without tripping over your own words.
If you’re interested in learning more about the arguments developers use to support maintaining the name-main idiom as-is, I recommend diving into some of the connected conversations taking place in the different Python community channels.