Wednesday, May 1, 2024
HomePythonWhat Does if __name__ == "__main__" Do in Python? – Actual Python

What Does if __name__ == “__main__” Do in Python? – Actual Python


You’ve doubtless encountered Python’s if __name__ == "__main__" idiom when studying different individuals’s code. No surprise—it’s widespread! You may need even used if __name__ == "__main__" in your personal scripts. However did you employ it appropriately?

Perhaps you’ve programmed in a C-family language like Java earlier than, and also you ponder whether this assemble is a careless accent to utilizing a major() operate as an entry level.

Syntactically, Python’s if __name__ == "__main__" idiom is only a regular conditional block:

 1if __name__ == "__main__":
 2    ...

The indented block beginning in line 2 comprises all of the code that Python will execute when the conditional assertion in line 1 evaluates to True. Within the code instance above, the precise code logic that you simply’d put within the conditional block is represented with a placeholder ellipsis (...).

So—if there’s nothing particular in regards to the if __name__ == "__main__" idiom, then why does it look complicated, and why does it proceed to spark dialogue within the Python neighborhood?

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, you then’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 solution to seek advice from it.

In Brief: 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 solution to retailer code that ought to solely run when your file is executed as a script.

You’ll see what which means in a second. For now, say you have got 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 operate, echo(), that mimics a real-world echo by progressively printing fewer and fewer of the ultimate letters of the enter textual content.

Under that, in strains 10 to 12, you employ the if __name__ == "__main__" idiom. This code begins with the conditional assertion if __name__ == "__main__" in line 10. Within the indented strains, 11 and 12, you then acquire consumer enter and name echo() with that enter. These two strains will execute if 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 below if then runs, so Python collects consumer enter and calls echo().

Attempt it out your self! You may 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 need 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 along 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 below the if __name__ == "__main__" idiom, you then keep away from working code that’s irrelevant for imported modules.

Nesting code below if __name__ == "__main__" lets you cater to totally different use circumstances:

  • Script: When run as a script, your code prompts the consumer for enter, calls echo(), and prints the outcome.
  • Module: Whenever you import echo as a module, then echo() will get outlined, however no code executes. You present echo() to the principle code session with none negative effects.

By implementing the if __name__ == "__main__" idiom in your code, you arrange an extra entry level that lets you 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 assist you 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 seek advice from it for brief.

How Does the Title-Most important Idiom Work?

At its core, the idiom is a conditional assertion that checks whether or not the worth of the variable __name__ is the same as the string "__main__":

  • If the __name__ == "__main__" expression is True, then the indented code following the conditional assertion executes.
  • If the __name__ == "__main__" expression is False, 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 if you run your Python file as a script from the command line. Whereas that covers most real-life use circumstances, perhaps you need to go deeper.

Python units the international __name__ of a module equal to "__main__" if the Python interpreter runs your code within the top-level code surroundings:

“High-level code” is the primary user-specified Python module that begins working. It’s “top-level” as a result of it imports all different modules that this system wants. (Supply)

To raised perceive what which means, 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__, sort(__name__))

Your new file comprises solely a single line of code that prints the worth and sort 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 reveals you that the worth of __name__ is the Python string "__main__" when you run your file as a script.

Now you already know the worth of __name__ when your code is executed within the top-level code surroundings.

However a conditional assertion can solely produce totally different outcomes when the situation has an opportunity to guage in several methods. So, when is your code not run within the top-level code surroundings, and what occurs to the worth of __name__ in that case?

The code in your file isn’t run within the top-level code surroundings when you import your module. In that case, Python units __name__ to the module’s identify.

To do this 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 in the course of the import, which suggests it’ll name print(__name__, sort(__name__)) and write the output to the console.

On this case, nonetheless, the worth of the module’s __name__ is totally different. It factors to "namemain", a string that’s equal to the module’s identify.

You simply discovered that on your top-level code surroundings, __name__ is all the time "__main__", so go forward and make sure that inside your interpreter session. Additionally test 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.

Now you already know that the worth of __name__ could have one in every of two values relying on the place it lives:

  • In the top-level code surroundings, 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 working within the top-level code surroundings. 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__, sort(__name__))

if __name__ == "__main__":
    print("Nested code solely runs within the top-level code surroundings")

With this conditional test in place, you possibly can declare code that solely executes when the module is run within the top-level code surroundings.

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 surroundings

When working 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 below if __name__ == "__main__" doesn’t execute.

Now that you understand how the name-main idiom works in Python, you could surprise when and the way precisely you must use it in your code—and when to keep away from it!

When Ought to You Use the Title-Most important Idiom in Python?

You employ this idiom if you need to create an extra entry level on 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 part of this tutorial, you used the name-main idiom along with enter() to gather consumer enter when working echo.py as a script. That’s a terrific cause to make use of the name-main idiom!

There are additionally different methods to gather consumer enter immediately from the command line. For instance, you 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 amassing consumer enter with enter(), you modified the code in echo.py in order that your customers can present the textual content as arguments immediately from the command line:

$ python echo.py HELLOOOOO ECHOOOO
ooo
oo
o
.

Python collects an arbitrary variety of phrases into sys.argv, which is a listing 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 bundle, then you must create a devoted __main__.py file for that function. This file represents an entry level that Python invokes if you run your bundle utilizing the -m choice:

Whenever you create a digital surroundings utilizing the venv module, as proven above, you then run code outlined in a __main__.py file. The -m choice adopted by the module identify venv invokes __main__.py from the venv module.

As a result of venv is a bundle moderately than a small command-line interface (CLI) script, it has a devoted __main__.py file as its entry level.

Within the wild, you could encounter many extra causes for utilizing the name-main idiom in Python code. Nonetheless, amassing consumer enter, both by means of customary enter or the command-line, is the first advised cause for utilizing it.

When Ought to You Keep away from the Title-Most important 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 the very best thought to make use of it. You might be stunned to study that in lots of circumstances, there are higher choices than nesting your code below if __name__ == "__main__" in Python.

Typically, builders use the name-main idiom so as to add check runs to a script that mixes code performance and exams 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.major()

With this setup, you possibly can run exams in opposition to your code if 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 referred to as unittest.major(). 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 doable to import the module and use the operate that you simply’ve outlined there. The unit check gained’t run until you execute the module within the top-level code surroundings.

Whereas this works for small information, it’s usually not thought of good observe. It’s not suggested to combine exams and code in the identical file. As an alternative, write your exams in a separate file. Following this recommendation usually makes for a extra organized code base. This method additionally removes any overhead, resembling the necessity to import unittest in your major 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{'-' * 42}n")
    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 might discover such demo code executions within the name-main idiom, however there are arguably significantly better methods to exhibit use your program. You may write detailed docstrings with instance runs that may double as doctests, and you may compose correct documentation on your undertaking.

The earlier two examples cowl two widespread suboptimal use circumstances of the name-main idiom. There are additionally different eventualities when it’s greatest to keep away from the name-main idiom in Python:

  • A pure script: If you happen to 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 if you program in Python.

  • A fancy command-line program: If you happen to write a bigger command-line software, then it’s greatest 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 advanced command-line packages, you’ll additionally profit from utilizing the built-in argparse module as a substitute of sys.argv.

Perhaps you’ve used the name-main idiom for one in every of these suboptimal functions earlier than. If you wish to study extra about write extra idiomatic Python for every of those eventualities, then observe the supplied hyperlinks:

Though you now know when to keep away from the name-main idiom, you may nonetheless surprise about greatest use it in a legitimate state of affairs.

In What Manner Ought to You Embrace the Title-Most important Idiom?

The name-main idiom in Python is only a conditional assertion, so you can use it anyplace in your file—much more than as soon as! For many use circumstances, nonetheless, you’ll put one name-main idiom on the backside of your script:

# All of your code

if __name__ == "__main__":
    ...

You set the name-main idiom on the finish of your script as a result of the entry level for a Python script is all the time the highest of the file. If you happen to put the name-main idiom on the backside of your file, then all of your capabilities and courses get outlined earlier than Python evaluates the conditional expression.

Nonetheless, though it’s unusual to make use of multiple name-main idiom in a script, there could also be a cause to take action in some circumstances. Python’s model information doc, PEP 8, is obvious about the place to place all of your import statements:

Imports are all the time put on the high of the file, simply after any module feedback and docstrings, and earlier than module globals and constants. (Supply)

This is the reason you imported sys on the high 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))

Nonetheless, you don’t even have to import sys in any respect if you merely need to import echo as a module.

To handle this and nonetheless keep on with the model solutions outlined in PEP 8, you 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 high of the file however keep away from importing sys if 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 below one other name-main idiom. That means, you retain the import assertion on the high of your file, however you keep away from importing sys if you use echo as a module.

As you discovered earlier within the tutorial, there are fewer events to make use of the name-main idiom than you may anticipate. For many of these use circumstances, placing one in every of these conditional checks on the backside of your script will likely be your best option.

Lastly, you could surprise what code ought to go into the conditional code block. The Python documentation provides clear steering in regards to the idiomatic utilization of the name-main idiom in that regard:

Placing as few statements as doable within the block beneath if __name___ == '__main__' can enhance code readability and correctness. (Supply)

Preserve the code below your name-main idiom to a minimal! Whenever you begin placing a number of strains of code nested below the name-main idiom, then you must as a substitute outline a major() operate and name that operate:

# 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 major() -> None:
    textual content = " ".be part of(sys.argv[1:])
    print(echo(textual content))

if __name__ == "__main__":
    major()

This design sample provides you the benefit that the code below the name-main idiom is obvious and concise. Moreover, it makes it doable to name major() even when you’ve imported your code as a module, for instance to unit check its capabilities.

On this part, you’ve discovered that you must in all probability write the name-main idiom on the backside of your script.

You probably have a number of strains of code that you simply’re planning to nest below if __name__ == "__main__", then it’s higher to refactor that code right into a major() operate that you simply name from the conditional block below the name-main idiom.

Now that you understand how you should utilize the name-main idiom, you could surprise why it seems extra cryptic than different Python code that you simply’re used to.

Is the Idiom Boilerplate Code That Ought to Be Simplified?

If you happen to’re coming from a special object-oriented programming language, you may suppose that Python’s name-main idiom is an entry level akin to the major() capabilities in Java or C, however clumsier:

The Power Rangers and Teletubby meme with text about main functions and Python's if __name__ equal to "__main__"
Meme primarily based on an internet comedian (Picture: Mike Organisciak)

Whereas undoubtedly humorous and relatable, this meme is deceptive as a result of it implies that the name-main idiom is corresponding to major() entry level capabilities in different languages.

Python’s name-main idiom isn’t particular. It’s only a conditional test. It could look cryptic at first, particularly if you’re beginning to work with Python and also you’re used to Python’s slim and stylish syntax. In any case, the name-main idiom features a dunder variable from the worldwide namespace, and a string that’s a dunder worth as properly.

So it’s not the kind of entry level that major represents in different languages. However why does it look the best way it does? You could have copied and pasted the idiom many occasions, and even typed it out, and questioned why Python doesn’t have a extra concise syntax for it.

If you happen to browse the archives of the Python-ideas mailing record, rejected PEPs, and the Python dialogue discussion board, you then’ll discover a variety of makes an attempt to vary the idiom.

If you happen to learn a few of these discussions, you then’ll discover that many seasoned Pythonistas argue that the idiom isn’t cryptic and shouldn’t be modified. They provide a number of causes:

  • It’s brief: Most advised modifications save solely two strains of code.
  • It has a restricted use case: It is best to solely use it if you have 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 a giant 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 below 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 intervening time. It looks like it’d be useful to search out a great way to seek advice from it constantly and concisely!

Develop the part beneath for a little bit of context and some solutions on how you can discuss in regards to 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 write down and much more cumbersome to say out loud, so that you may as properly discover a great way to speak about it.

There are alternative ways to seek advice from it within the Python neighborhood. Most mentions on-line embrace the entire if __name__ == "__main__" expression adopted by a phrase:

  • The if __name__ == "__main__" conference (Supply)
  • The if __name__ == "__main__" expression (Supply)
  • The if __name__ ... idiom (Supply)
  • The if __name__ == "__main__": ... idiom (Supply)
  • The if __name__ == "__main__" idiom (Supply)
  • The executable stanza (Supply)

As you could discover, there’s no strict conference round speak about if __name__ == "__main__", however you in all probability gained’t do mistaken when you observe the overall consensus of calling it the if __name__ == "__main__" idiom.

If you wish to promote standardizing a shorter identify for the idiom, then inform your mates to name it the name-main idiom. That’s what we’ll be calling it at Actual Python! If you happen to discover the time period helpful, then perhaps it’ll catch on.

If you happen to’re curious, take a plunge into a number of the linked discussions within the varied Python neighborhood channels to study extra about why builders argue for holding the name-main idiom as it’s.

Conclusion

You’ve discovered what the if __name__ == "__main__" idiom does in Python. It lets you write code that executes if you run the file as a script, however not if you import it as a module. It’s greatest to make use of it if you need to acquire consumer enter throughout a script run and keep away from negative effects when importing your module—for instance, to unit check its capabilities.

You additionally bought to know some widespread however suboptimal use circumstances and discovered about higher and extra idiomatic approaches you could absorb 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 you could in all probability change its use most often.

When do you employ the name-main idiom in your Python code? Whereas studying this tutorial, did you uncover a solution to change it, or is there a great use case that we missed? Share your ideas within the feedback beneath.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments