What does the if __name__ ==


This article explains what the Python code expression if __name__ == '__main__' means.

A Python programme uses the condition if __name__ == '__main__' to only run the code inside the if statement when the program is run directly by the Python interpreter. The code inside the if statement is not executed when the file's code is imported as a module.

What is __main__?

The word "__name__" denotes a unique variable in Python.

Python has a large number of special variables that begin and end with double underscores. They are referred to as dunder to keep it brief (from Double Underscores). In this case, "__name__" is pronounced "dunder name."

Let's use the Python shell to determine what the value of __main__ −

>>> __name__
'__main__'

So, the value of __name__ is __main__.

Let's try importing a Python module to see the value assigned to the module's __name__ variable −

>>> import random
>>> random.__name__
'random'

So, after importing the random module, we can see that the value for __name__ is 'random,' which is essentially its name.

Python __name__ variable values

Make the following code and place it in the file __name__main.py −

print(" __name__ value is {}".format(__name__))

A single print command that outputs the value of __name__ using the string formatting method.

The value of __name__ is __main__ when we run the code directly by referencing the Python file −

$ python __name__main.py 
The value of __name__ is __main__

Instead, the value of __name__ if we import the module via the Python shell is __name__main −

>>> import _name_main
__name__ value is __name__main

So, the value of __name__ varies depending on how our Python code is executed.

Example of __name__

To use the condition if__name__== “__main__” in Python , a python program is created as shown below by which three different functions are called −

def step1(): print("Executing the first step...") def step2(): print("Executing the second step...") def step3(): print("Executing the third step...") step1() step2() step3()

Output

Following is an output of the above code −

Executing the first step...
Executing the second step...
Executing the third step...

Let's imagine a different Python application needs to use the step1 function (). We would need to import our file as a module to accomplish that.

What occurs when we do that is as follows −

>>> import _name_main Executing the first step... Executing the second step... Executing the third step... >>> _name_main.step1() Executing the first step...

The step1() function can be called after the module has been imported. The issue is that the following three lines are automatically executed when we import the module −

step1()
step2()
step3()

Now the question is- How do we prevent that?

Checking if __name__ is equals to __main__ when the module is imported

We may verify that the value of __name__ is equal to "__main__" to stop the behaviour occurring which we saw in the previous section.

In this manner, the Python file's code inside the if condition is only run when it is directly called rather than when it is imported as a module.

Example

Now, the program is −

def step1(): print("Executing the first step...") def step2(): print("Executing the second step...") def step3(): print("Executing the third step...") if __name__ == "__main__": step1() step2() step3()

Output

Let's check that calling the Python program directly still invokes the three functions

Executing the first step...
Executing the second step...
Executing the third step...

Additionally, when we import this as a module, the three functions are not executed 7minus;

>>> import _name_main >>> _name_main.step1() Executing the first step...

This time it's much better!

Consider that the _name_main module has hundreds of functions, not all of which you want to import.

How can the step1() function be imported simply?

The following syntax should be used −

>>> from _name_main import step1
>>> step1()
Executing step1...
>>> step2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'step2' is not defined

As you can see, in this instance, we only imported the successful version of the function step1.

NameError: name'step2' is not defined occurs when we attempt to run step2().

Main method in Python

In languages like Java or C, the concept of main is quite common and designates the starting point for a program's execution.

The main() function, which is frequently used in Python, is executed inside the if statement and verifies the value of the __name__ variable.

To get a certain result, several functions are called in the main() function.In our situation, the main function would call the three subfunctions −

Example

def step1(): print("Executing the first step...") def step2(): print("Executing the second step...") def step3(): print("Executing the third step...") def main(): step1() step2() step3() if __name__ == "__main__": main()

Output

Executing the first step...
Executing the second step...
Executing the third step...

Since the concept of main is widely-known to other developers as well, designating the function main() is just a standard naming convention that improves the readability of the program.

Actually, nothing prevents us from renaming the main function to something else.

Verify that our revised code functions properly in both circumstances before moving on with this article −

  • direct execution of code
  • importing the module

__name__, __main__ and Arguments in Python

We may handle any parameters supplied to our Python program when called right inside the if condition that determines if the variable __name__ is equal to "__main__."

We can use the sys module to handle parameters given to the program.

  • Imported the sys module.

  • Create a function called main() that only accepts one argument. A list of strings containing the arguments supplied to the program when it is performed will make up this argument.

  • As part of the if statement, which checks the value of the __name__ variable, provide sys.argv to the main() function.

Example

import sys def main(args): print(args) if __name__ == "__main__": main(sys.argv)

Output

Following is the output of the above executed program −

['main.py']

As you can see, the Python program's first argument is the name of the .py file itself.

Let's modify the main method such that it prints the args variable's type.

def main(args): print(type(args)) print(args)

This proves that args is a list −

$ python arguments.py arg1 arg2 <class 'list'> ['arguments.py', 'arg1', 'arg2']

In addition to supplying arguments, we can also unpack the arguments our program needs, excluding the program's name −

import sys def main(c, d): return int(c) * int(d) if __name__ == "__main__": arg1, arg2 = sys.argv[1:3] print(main(arg1, arg2))

Here are the steps we took to execute the program and the outcomes we received −

$ python product.py 4 5
20

The two numbers given on the command line are taken by this code using the slicing operator. The two numbers are then given to the main() method while still being in string format.

The result of the two numbers being transformed to integers is then returned by the main function.

Updated on: 23-Aug-2023

82K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements