×

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

Python Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

5 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Python set()

Python set() Class The set() class in Python returns a new set object, optionally with elements taken from iterable.  Syntax class set([iterable]) Parameter iterable : This parameter represents a sequence, collection or an iterator object Return This function returns a...

1 minute read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Python Dictionary fromkeys() method

Python Dictionary fromkeys() method The dictionary.fromkeys() method in Python creates a new dictionary from the given sequence of elements and returns a dictionary with the specified keys and values. Syntax dictionary.fromkeys(sequence[, value]) Parameter sequence- This...

1 minute read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.