You’ve possible encountered Python’s if __name__ == "__main__"
idiom when studying different individuals’s code. No marvel—it’s widespread! You may need even used if __name__ == "__main__"
in your individual scripts. However did you utilize it appropriately?
Perhaps you’ve programmed in a C-family language like Java earlier than, and also you ponder whether this assemble is a slipshod accent to utilizing a essential()
perform as an entry point.
Syntactically, Python’s if __name__ == "__main__"
idiom is only a regular conditional block:
1if __name__ == "__main__":
2 ...
The indented block beginning in line 2 incorporates all of the code that Python will execute when the conditional assertion in line 1 evaluates to True
. Within the code instance above, the particular code logic that you simply’d put within the conditional block is represented with a placeholder ellipsis (...
).
So—if there’s nothing particular concerning the if __name__ == "__main__"
idiom, then why does it look complicated, and why does it proceed to spark dialogue within the Python group?
If the idiom nonetheless appears a bit of cryptic, and also you’re not fully positive what it does, why you may want it, and when to make use of it, then you definitely’ve come to the appropriate place! On this tutorial, you’ll study all about Python’s if __name__ == "__main__"
idiom—beginning with what it actually does in Python, and ending with a suggestion for a faster technique to check with it.
In Quick: It Permits You to Execute Code When the File Runs as a Script, however Not When It’s Imported as a Module
For many sensible functions, you possibly can consider the conditional block that you simply open with if __name__ == "__main__"
as a technique to retailer code that ought to solely run when your file is executed as a script.
You’ll see what meaning in a second. For now, say you will have the next file:
1# echo.py
2
3def echo(textual content: str, repetitions: int = 3) -> str:
4 """Imitate a real-world echo."""
5 echoed_text = ""
6 for i in vary(repetitions, 0, -1):
7 echoed_text += f"textual content[-i:]n"
8 return f"echoed_text.decrease()."
9
10if __name__ == "__main__":
11 textual content = enter("Yell one thing at a mountain: ")
12 print(echo(textual content))
On this instance, you outline a perform, echo()
, that mimics a real-world echo by step by step printing fewer and fewer of the ultimate letters of the enter textual content.
Under that, in traces 10 to 12, you utilize the if __name__ == "__main__"
idiom. This code begins with the conditional assertion if __name__ == "__main__"
in line 10. Within the indented traces, 11 and 12, you then gather consumer enter and name echo()
with that enter. These two traces will execute while you run echo.py
as a script out of your command line:
$ python echo.py
Yell one thing at a mountain: HELLOOOO ECHOOOOOOOOOO
ooo
oo
o
.
Whenever you run the file as a script by passing the file object to your Python interpreter, the expression __name__ == "__main__"
returns True
. The code block underneath if
then runs, so Python collects consumer enter and calls echo()
.
Strive it out your self! You possibly can obtain all of the code information that you simply’ll use on this tutorial from the hyperlink beneath:
On the similar time, when you import echo()
in one other module or a console session, then the nested code gained’t run:
>>> from echo import echo
>>> print(echo("Please assist me I am caught on a mountain"))
ain
in
n
.
On this case, you wish to use echo()
within the context of one other script or interpreter session, so that you gained’t want to gather consumer enter. Operating enter()
would mess together with your code by producing a aspect impact when importing echo
.
Whenever you nest the code that’s particular to the script utilization of your file underneath the if __name__ == "__main__"
idiom, then you definitely keep away from operating code that’s irrelevant for imported modules.
Nesting code underneath if __name__ == "__main__"
permits you to cater to completely different use circumstances:
- Script: When run as a script, your code prompts the consumer for enter, calls
echo()
, and prints the consequence. - Module: Whenever you import
echo
as a module, thenecho()
will get outlined, however no code executes. You presentecho()
to the primary code session with none negative effects.
By implementing the if __name__ == "__main__"
idiom in your code, you arrange an extra entry level that permits you to use echo()
proper from the command line.
There you go! You’ve now lined crucial details about this matter. Nonetheless, there’s extra to search out out, and there are some subtleties that may allow you to construct a deeper understanding of this code particularly and Python extra usually.
Learn on to study extra about the name-main idiom, as this tutorial will check with it for brief.
How Does the Title-Major Idiom Work?
At its core, the idiom is a conditional statement that checks whether or not the worth of the variable __name__
is the same as the string "__main__"
:
- If the
__name__ == "__main__"
expression isTrue
, then the indented code following the conditional assertion executes. - If the
__name__ == "__main__"
expression isFalse
, then Python skips the indented code.
However when is __name__
equal to the string "__main__"
? Within the earlier part, you discovered that that is the case while you run your Python file as a script from the command line. Whereas that covers most real-life use circumstances, perhaps you wish to go deeper.
Python units the global __name__
of a module equal to "__main__"
if the Python interpreter runs your code within the top-level code setting:
“Prime-level code” is the primary user-specified Python module that begins operating. It’s “top-level” as a result of it imports all different modules that this system wants. (Source)
To higher perceive what meaning, you’ll arrange a small sensible instance. Create a Python file, name it namemain.py
, and add one line of code:
# namemain.py
print(__name__, kind(__name__))
Your new file incorporates solely a single line of code that prints the worth and type of the worldwide __name__
to the console.
Spin up your terminal and run the Python file as a script:
$ python namemain.py
__main__ <class 'str'>
The output exhibits you that the worth of __name__
is the Python string "__main__"
when you run your file as a script.
Word: Within the top-level code setting, the worth of __name__
is at all times "__main__"
. The highest-level code setting is commonly a module that you simply move to the Python interpreter as a file argument, as you noticed above. Nevertheless, there are different choices that may represent the top-level code setting:
- The scope of an interactive immediate
- The Python module or bundle handed to the Python interpreter with the
-m
option, which stands for module - Python code learn by the Python interpreter from customary enter
- Python code handed to the Python interpreter with the
-c
option, which stands for command
Should you’re curious to study extra about these choices, then take a look at the Python documentation on what the top-level code environment is. The documentation illustrates every of those bullet factors with a concise code snippet.
Now you understand the worth of __name__
when your code is executed within the top-level code setting.
However a conditional assertion can solely produce completely different outcomes when the situation has an opportunity to guage in numerous methods. So, when is your code not run within the top-level code setting, and what occurs to the worth of __name__
in that case?
The code in your file isn’t run within the top-level code setting when you import your module. In that case, Python units __name__
to the module’s identify.
To do that out, begin a Python console and import the code from namemain.py
as a module:
>>> import namemain
namemain <class 'str'>
Python executes the code saved within the international namespace of namemain.py
throughout the import, which suggests it’ll name print(__name__, kind(__name__))
and write the output to the console.
On this case, nevertheless, the worth of the module’s __name__
is completely different. It factors to "namemain"
, a string that’s equal to the module’s identify.
Word: You possibly can import any file that incorporates Python code as a module, and Python will run the code in your file throughout import. The identify of the module will normally be the filename with out the file extension for Python information (.py
).
You simply discovered that in your top-level code setting, __name__
is at all times "__main__"
, so go forward and ensure that inside your interpreter session. Additionally examine the place the string "namemain"
comes from:
>>> __name__
'__main__'
>>> namemain.__name__
'namemain'
The worldwide __name__
has the worth "__main__"
, and .__name__
for the imported namemain
module has the worth "namemain"
, which is the module’s identify as a string.
Word: More often than not, the top-level code setting would be the Python script that you simply execute and the place you’re importing different modules. Nevertheless, on this instance, you possibly can see that the top-level code setting isn’t strictly tied to a script run and will also be, for instance, an interpreter session.
Now you understand that the worth of __name__
can have one among two values relying on the place it lives:
- In the top-level code setting, the worth of
__name__
is"__main__"
. - In an imported module, the worth of
__name__
is the module’s identify as a string.
As a result of Python follows these guidelines, you will discover out whether or not or not a module is operating within the top-level code setting. You do that by checking the worth of __name__
with a conditional assertion, which brings you full circle to the name-main idiom:
# namemain.py
print(__name__, kind(__name__))
if __name__ == "__main__":
print("Nested code solely runs within the top-level code setting")
With this conditional examine in place, you possibly can declare code that solely executes when the module is run within the top-level code setting.
Add the idiom to namemain.py
as proven within the code block above, then run the file as a script as soon as extra:
$ python namemain.py
__main__ <class 'str'>
Nested code solely runs within the top-level code setting
When operating your code as a script, each calls to print()
execute.
Subsequent, begin a brand new interpreter session and import namemain
as a module as soon as extra:
>>> import namemain
namemain <class 'str'>
Whenever you import your file as a module, the code that you simply nested underneath if __name__ == "__main__"
doesn’t execute.
Now that you understand how the name-main idiom works in Python, chances are you’ll marvel when and the way precisely you need to use it in your code—and when to keep away from it!
When Ought to You Use the Title-Major Idiom in Python?
You utilize this idiom while you wish to create an extra entry level in your script, in order that your file is accessible as a stand-alone script in addition to an importable module. You may want that when your script wants to gather consumer enter.
Within the first section of this tutorial, you used the name-main idiom along with enter()
to gather consumer enter when operating echo.py
as a script. That’s an awesome cause to make use of the name-main idiom!
There are additionally different methods to gather consumer enter straight from the command line. For instance, you possibly can create a command-line entry level for a small Python script with sys.argv
and the name-main idiom:
1# echo.py
2
3import sys
4
5def echo(textual content: str, repetitions: int = 3) -> str:
6 """Imitate a real-world echo."""
7 echoed_text = ""
8 for i in vary(repetitions, 0, -1):
9 echoed_text += f"textual content[-i:]n"
10 return f"echoed_text.decrease()."
11
12if __name__ == "__main__":
13 textual content = " ".be part of(sys.argv[1:])
14 print(echo(textual content))
As an alternative of gathering consumer enter with enter()
, you modified the code in echo.py
in order that your customers can present the textual content as arguments straight from the command line:
$ python echo.py HELLOOOOO ECHOOOO
ooo
oo
o
.
Python collects an arbitrary variety of phrases into sys.argv
, which is an inventory of strings that represents all inputs. Every phrase is taken into account a brand new argument when a whitespace character separates it from the others.
By taking the code execution that handles consumer enter and nesting it within the name-main idiom, you present an extra entry level to your script.
If you wish to create an entry level for a package, then you need to create a devoted __main__.py
file for that goal. This file represents an entry level that Python invokes while you run your bundle utilizing the -m
option:
Whenever you create a virtual environment utilizing the venv
module, as proven above, then you definitely run code outlined in a __main__.py
file. The -m
possibility adopted by the module identify venv
invokes __main__.py
from the venv
module.
As a result of venv
is a bundle fairly than a small command-line interface (CLI) script, it has a devoted __main__.py
file as its entry level.
Word: There are further benefits of nesting code, akin to consumer enter assortment, underneath the name-main idiom. As a result of that nested code doesn’t execute throughout module imports, you possibly can run unit tests from a separate testing module in your features with out producing negative effects.
Negative effects may in any other case happen as a result of a testing module must import your module to run checks towards your code.
Within the wild, chances are you’ll encounter many extra causes for utilizing the name-main idiom in Python code. Nevertheless, gathering consumer enter, both by way of customary enter or the command-line, is the first instructed cause for utilizing it.
When Ought to You Keep away from the Title-Major Idiom?
Now that you simply’ve discovered when to make use of the name-main idiom, it’s time to search out out when it’s not one of the best thought to make use of it. You could be shocked to study that in lots of circumstances, there are higher choices than nesting your code underneath if __name__ == "__main__"
in Python.
Generally, builders use the name-main idiom so as to add check runs to a script that mixes code performance and checks in the identical 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.essential()
With this setup, you possibly can run checks towards your code while you execute it as a script:
$ python adder.py
.
----------------------------------------------------------------------
Ran 1 check in 0.000s
OK
Since you ran the file as a script, __name__
was equal to "__main__"
, the conditional expression returned True
, and Python known as unittest.essential()
. The tiny check suite ran, and your check succeeded.
On the similar time, you didn’t create any sudden code execution when importing your code as a module:
>>> import adder
>>> adder.add(1, 2)
3
It’s nonetheless potential to import the module and use the perform that you simply’ve outlined there. The unit check gained’t run until you execute the module within the top-level code setting.
Whereas this works for small information, it’s usually not thought of good apply. It’s not suggested to combine checks and code in the identical file. As an alternative, write your checks in a separate file. Following this recommendation usually makes for a extra organized code base. This method additionally removes any overhead, akin to the necessity to import unittest
in your essential script file.
Another excuse that some programmers use the name-main idiom is to incorporate a demonstration of what their code can do:
# echo_demo.py
def echo(textual content: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in vary(repetitions, 0, -1):
echoed_text += f"textual content[-i:]n"
return f"echoed_text.decrease()."
if __name__ == "__main__":
print('Instance name: echo("HELLO", repetitions=2)', finish=f"n'-' * 42n")
print(echo("HELLO", repetitions=2))
Once more, your customers can nonetheless import the module with none negative effects. Moreover, after they run echo_demo.py
as a script, they get a peek at its performance:
$ python echo_demo.py
Instance name: echo("HELLO", repetitions=2)
------------------------------------------
lo
o
.
You could discover such demo code executions within the name-main idiom, however there are arguably a lot better methods to display find out how to use your program. You possibly can write detailed docstrings with instance runs that may double as doctests, and you may compose correct documentation in your venture.
The earlier two examples cowl two frequent suboptimal use circumstances of the name-main idiom. There are additionally different eventualities when it’s finest to keep away from the name-main idiom in Python:
-
A pure script: Should you write a script that’s meant to be run as a script, then you possibly can put your code execution into the worldwide namespace with out nesting it within the name-main idiom. You can use Python as a scripting language as a result of it doesn’t implement robust object-oriented patterns. You don’t have to stay to design patterns from different languages while you program in Python.
-
A fancy command-line program: Should you write a bigger command-line software, then it’s finest to create a separate file as your entry level. You then import the code out of your module there as a substitute of dealing with consumer enter with the name-main idiom. For extra complicated command-line packages, you’ll additionally profit from utilizing the built-in
argparse
module as a substitute ofsys.argv
.
Perhaps you’ve used the name-main idiom for one among these suboptimal functions earlier than. If you wish to study extra about find out how to write more idiomatic Python for every of those eventualities, then observe the supplied hyperlinks:
Regardless that you now know when to keep away from the name-main idiom, you may nonetheless marvel about find out how to finest use it in a legitimate state of affairs.
In What Approach Ought to You Embody the Title-Major Idiom?
The name-main idiom in Python is just a conditional statement, so you possibly can use it wherever in your file—much more than as soon as! For many use circumstances, nevertheless, you’ll put one name-main idiom on the backside of your script:
# All of your code
if __name__ == "__main__":
...
You place the name-main idiom on the finish of your script as a result of the entry level for a Python script is at all times the highest of the file. Should you put the name-main idiom on the backside of your file, then all of your features and courses get outlined earlier than Python evaluates the conditional expression.
Nevertheless, though it’s unusual to make use of a couple of name-main idiom in a script, there could also be a cause to take action in some circumstances. Python’s fashion information doc, PEP 8, is evident about the place to place all of your import statements:
Imports are at all times put on the prime of the file, simply after any module feedback and docstrings, and earlier than module globals and constants. (Source)
This is the reason you imported sys
on the prime of the file in echo.py
:
# echo.py
import sys
def echo(textual content: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in vary(repetitions, 0, -1):
echoed_text += f"textual content[-i:]n"
return f"echoed_text.decrease()."
if __name__ == "__main__":
textual content = " ".be part of(sys.argv[1:])
print(echo(textual content))
Nevertheless, you don’t even have to import sys
in any respect while you merely wish to import echo
as a module.
To deal with this and nonetheless persist with the fashion strategies outlined in PEP 8, you possibly can use a second name-main idiom. By nesting the import of sys
in a name-main idiom, you possibly can hold all imports on the prime of the file however keep away from importing sys
while you gained’t want to make use of it:
# echo.py
if __name__ == "__main__":
import sys
def echo(textual content: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in vary(repetitions, 0, -1):
echoed_text += f"textual content[-i:]n"
return f"echoed_text.decrease()."
if __name__ == "__main__":
textual content = " ".be part of(sys.argv[1:])
print(echo(textual content))
You nested the import of sys
underneath one other name-main idiom. That manner, you retain the import assertion on the prime of your file, however you keep away from importing sys
while you use echo
as a module.
Word: You possible gained’t encounter this setup steadily, but it surely serves for instance of when it might be useful to make use of a number of name-main idioms in a single file.
Nonetheless, readability counts, so maintaining the import assertion on the prime with out the second name-main idiom will usually be the higher alternative. Nevertheless, a second name-main idiom may turn out to be useful when you’re working in an setting with restricted resources.
As you discovered earlier within the tutorial, there are fewer events to use the name-main idiom than you may anticipate. For many of these use circumstances, placing one among these conditional checks on the backside of your script can be your best option.
Lastly, chances are you’ll marvel what code ought to go into the conditional code block. The Python documentation gives clear steerage concerning the idiomatic utilization of the name-main idiom in that regard:
Placing as few statements as potential within the block beneath
if __name___ == '__main__'
can enhance code readability and correctness. (Source)
Hold the code underneath your name-main idiom to a minimal! Whenever you begin placing a number of traces of code nested underneath the name-main idiom, then you need to as a substitute define a main()
function and name that perform:
# echo.py
import sys
def echo(textual content: str, repetitions: int = 3) -> str:
"""Imitate a real-world echo."""
echoed_text = ""
for i in vary(repetitions, 0, -1):
echoed_text += f"textual content[-i:]n"
return f"echoed_text.decrease()."
def essential() -> None:
textual content = " ".be part of(sys.argv[1:])
print(echo(textual content))
if __name__ == "__main__":
essential()
This design sample offers you the benefit that the code underneath the name-main idiom is evident and concise. Moreover, it makes it potential to name essential()
even when you’ve imported your code as a module, for instance to unit check its features.
Word: Defining essential()
in Python means one thing completely different from in different languages, akin to Java and C. In Python, naming this perform essential is only a conference. You may identify the perform something—and as you’ve seen earlier than, you don’t even want to make use of it in any respect.
Different object-oriented languages outline a essential()
perform because the entry level for a program. In that case, the interpreter implicitly calls a perform named essential()
, and your program gained’t work with out it.
On this part, you’ve discovered that you need to in all probability write the name-main idiom on the backside of your script.
When you’ve got a number of traces of code that you simply’re planning to nest underneath if __name__ == "__main__"
, then it’s higher to refactor that code right into a essential()
perform that you simply name from the conditional block underneath the name-main idiom.
Now that you understand how you need to use the name-main idiom, chances are you’ll marvel why it appears extra cryptic than different Python code that you simply’re used to.
Is the Idiom Boilerplate Code That Ought to Be Simplified?
Should you’re coming from a distinct object-oriented programming language, you may assume that Python’s name-main idiom is an entry level akin to the essential()
features in Java or C, however clumsier:

Whereas positively humorous and relatable, this meme is deceptive as a result of it implies that the name-main idiom is similar to essential()
entry level features in different languages.
Python’s name-main idiom isn’t particular. It’s only a conditional examine. It might look cryptic at first, particularly while you’re beginning to work with Python and also you’re used to Python’s slim and stylish syntax. In spite of everything, the name-main idiom features a dunder variable from the worldwide namespace, and a string that’s a dunder worth as nicely.
So it’s not the kind of entry level that essential represents in different languages. However why does it look the way in which it does? You might have copied and pasted the idiom many instances, and even typed it out, and puzzled why Python doesn’t have a extra concise syntax for it.
Should you browse the archives of the Python-ideas mailing list, rejected PEPs, and the Python discussion forum, then you definitely’ll discover quite a few makes an attempt to vary the idiom.
Should you learn a few of these discussions, then you definitely’ll discover that many seasoned Pythonistas argue that the idiom isn’t cryptic and shouldn’t be modified. They offer a number of causes:
- It’s quick: Most instructed modifications save solely two traces of code.
- It has a restricted use case: You must solely use it if it’s worthwhile to run a file each as a module in addition to a script. You shouldn’t want to make use of it fairly often.
- It exposes complexity: Dunder variables and performance are an enormous a part of Python when you peek a bit deeper. That may make the present idiom an entry level for learners that sparks curiosity and offers them a primary look underneath the hood of Python’s syntax.
- It maintains backward compatibility: The name-main idiom has been a de facto customary within the language for a very long time, which implies that altering it will break backward compatibility.
Okay, so that you’re caught with if __name__ == "__main__"
in the interim. It looks like it’d be useful to search out a great way to check with it persistently and concisely!
Develop the part beneath for a little bit of context and some strategies on how you possibly can discuss concerning the name-main idiom with out twisting your tongue or knotting your fingers:
You’ll in all probability talk about utilizing the name-main idiom in some unspecified time in the future in your Python profession. It’s a protracted expression to put in writing and much more cumbersome to say out loud, so that you may as nicely discover a great way to speak about it.
There are other ways to check with it within the Python group. Most mentions on-line embrace the entire if __name__ == "__main__"
expression adopted by a phrase:
- The
if __name__ == "__main__"
conference (Source) - The
if __name__ == "__main__"
expression (Source) - The
if __name__ ...
idiom (Source) - The
if __name__ == "__main__": ...
idiom (Source) - The
if __name__ == "__main__"
idiom (Source) - The executable stanza (Source)
As chances are you’ll discover, there’s no strict conference round find out how to speak about if __name__ == "__main__"
, however you in all probability gained’t do fallacious when you observe the final consensus of calling it the if __name__ == "__main__"
idiom.
If you wish to promote standardizing a shorter identify for the idiom, then inform your pals to name it the name-main idiom. That’s what we’ll be calling it at Actual Python! Should you discover the time period helpful, then perhaps it’ll catch on.
Should you’re curious, take a plunge into a number of the linked discussions within the varied Python group channels to study extra about why builders argue for maintaining the name-main idiom as it’s.
Conclusion
You’ve discovered what the if __name__ == "__main__"
idiom does in Python. It permits you to write code that executes while you run the file as a script, however not while you import it as a module. It’s finest to make use of it while you wish to gather consumer enter throughout a script run and keep away from negative effects when importing your module—for instance, to unit check its features.
You additionally bought to know some frequent however suboptimal use circumstances and discovered about higher and extra idiomatic approaches that you would be able to soak up these eventualities. Perhaps you’ve accepted Python’s name-main idiom after studying extra about it, however when you nonetheless dislike it, then it’s good to know that you would be able to in all probability change its use normally.
When do you utilize the name-main idiom in your Python code? Whereas studying this tutorial, did you uncover a technique to change it, or is there a great use case that we missed? Share your ideas within the feedback beneath.