×

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in every program that will require creating a function or calling a particular function into the current program. In those cases, this statement is used to assign variables __name__ and __main__ to the file's name.

Every time before an execution of a program, the python interpreter will set a particular variable when it reads the file. In those variables "__name__" is also one variable. Every python file will be saved and recognized by an extension called ".py".

Python language has many modules, so every time we use a module, the python interpreter will set the variable __name__ as __main__. This will be the case only when the module is given in the main program. In other instances where the module is imported from another depending module, the __name__ variable will be assigned to the module's name.  

A module is a group of functions that contain python definitions and statements. A module can access many functions, classes, and also variables. Having modules makes the program look more understandable and easy to write because there will be no use in rewriting the whole code, which might make the code look complex.

To make the module more understandable, we use this if __name__==__main__ statement.

Let us look at an example code to understand this concept clearly.

Example

# Python program for execution
# the main program directly
print ("always executes")
 
if __name__ == "__main__":
    print ("executes only when invoked directly")
else:
    print ("executes when imported only")

Output:

What does the if __name__ == “__main__”: do

The code present in the first indentation level will get executed, but all the functions and class codes will not be executed.

As we can see in the above code, the if statement only allows the first indentation and will not execute the other statements. You can also test whether your scripts run directly or the scripts are being imported from other testing variables.

Let us look at another example code to see where we use this statement:

Example

# Suppose this is file.py.


print("before importing")
import math


print("before defining function_a")
def function_a():
    print("Function a")


print("before defining function_b")
def function_b():
    print("Function b {}".format(math.sqrt(110)))


print("Before __name__ guard")
if __name__ == '__main__':
    function_a()
    function_b()
print("After __name__ guard")

Output:

What does the if __name__ == “__main__”: do

Need of  if __name__==__main__

We have to call it out if we need to use a module by importing it from another one. Look at an example code.

Example

# Python program for execution
# function from directly 
def MY_function():
    print ("I am inside a function of a module")
 
# We can always test the function by calling it.
MY_function()

Output:

What does the if __name__ == “__main__”: do

In this code, we called out a function to execute that part. But without calling the function, we can approach it by the following technique.

Technique:

# Python program for using
# main program for function call.
if __name__ == "__main__":
    my_function()
 
import myscript
 
myscript.my_function()

Advantages of using if __name__==__main__

  • For every python module, there will be a __name__ that is defined, and if this is the main program, then it is __main__, so this primary variable indicates that this program is being standalone by the user. This can also respond simultaneously to the appropriate sequence.
  • Once you import this program into a module and then import it into the same program independently, the __name__ is set to be the module name you selected.
  • All these python files can be used multiple times and also could be used as an independent program.
  • Anytime a module is created, then that module will be a library. There is no need always to script it whenever it runs some units or other demos.
  • Executing a code in python will set up a temporary variable and import the script.

Conclusion

In this article, we have covered a topic called if __name__==__main__ statement in python. So far, we have covered the definition of the if __name__==__main__ statement. Why does this statement work differently on different types of code? Application of this statement using example codes. Other ways of importing the module. The importance of this statement in the code and, finally, the advantages of this if __name__==__main__ statement.


Related Topics

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python Dictionary setdefault() method

Python Dictionary setdefault() method The dictionary.setdefault () method in Python returns the value of the item with the specified key. Syntax dictionary.setdefault(keyname, value) Parameter keyname- This parameter represents the keyname of the item you want...

1 minute read.

Python Pickle

The pickle is a module that enables serialization and de-serialization of the structure of the object in python. Pickling is the process that uses the protocols to convert the Python...

5 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Handling missing keys in Python dictionaries

In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value...

3 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

File Explorer using Tkinter in Python

File Explorer: Users can control folders and files on a device using an application known as a file manager or file explorer. Customers can access, edit, copy, delete, and start moving files...

3 minutes read.

How to implement classifiers in Python

What is classification? Classification is a type of supervised machine learning problem with a categorical target (response) variable. Given the known label in the training data, the classifier approximates a mapping...

4 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Paramiko Python Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.